Fake News Image Detector

import tkinter as tk

from tkinter import filedialog, messagebox

from PIL import Image, ImageTk

import exifread

import requests

import io


# -----------------------

# Metadata Extraction

# -----------------------

def extract_metadata(image_path):

    with open(image_path, 'rb') as f:

        tags = exifread.process_file(f)

    return {tag: str(tags[tag]) for tag in tags.keys()}


# -----------------------

# Reverse Search (TinEye / Google)

# -----------------------

def reverse_search(image_path):

    # Normally we would use an API like TinEye or Google Custom Search.

    # For demo, we simulate by uploading image to https://postimages.org and returning link.

    try:

        with open(image_path, 'rb') as f:

            files = {"file": f}

            r = requests.post("https://api.imgbb.com/1/upload",

                              files=files,

                              params={"key": "YOUR_IMGBB_API_KEY"})

            if r.status_code == 200:

                return r.json()["data"]["url"]

    except Exception as e:

        return f"Reverse search not available: {e}"

    return "Reverse search failed."


# -----------------------

# GUI Functions

# -----------------------

def open_image():

    file_path = filedialog.askopenfilename(filetypes=[("Image Files", "*.jpg;*.jpeg;*.png")])

    if not file_path:

        return


    # Show image

    img = Image.open(file_path)

    img.thumbnail((250, 250))

    img_tk = ImageTk.PhotoImage(img)

    lbl_image.config(image=img_tk)

    lbl_image.image = img_tk


    # Metadata

    metadata = extract_metadata(file_path)

    txt_metadata.delete(1.0, tk.END)

    if metadata:

        for k, v in metadata.items():

            txt_metadata.insert(tk.END, f"{k}: {v}\n")

    else:

        txt_metadata.insert(tk.END, "No metadata found.\n")


    # Reverse search (optional)

    link = reverse_search(file_path)

    txt_metadata.insert(tk.END, f"\nšŸ” Reverse Search Hint: {link}\n")


# -----------------------

# Main App

# -----------------------

root = tk.Tk()

root.title("šŸ“° Fake News Image Detector")

root.geometry("600x500")


frame_top = tk.Frame(root)

frame_top.pack(pady=10)


btn_upload = tk.Button(frame_top, text="šŸ“¤ Upload Image", command=open_image, font=("Arial", 12, "bold"))

btn_upload.pack()


lbl_image = tk.Label(root)

lbl_image.pack(pady=10)


lbl_meta = tk.Label(root, text="Image Metadata & Clues:", font=("Arial", 12, "bold"))

lbl_meta.pack()


txt_metadata = tk.Text(root, wrap=tk.WORD, width=70, height=15)

txt_metadata.pack(pady=10)


root.mainloop()


Smart Parking System Simulator pro

import tkinter as tk

from tkinter import messagebox

import sqlite3

import random


# -----------------------

# Database Setup

# -----------------------

def init_db():

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

    cur = conn.cursor()

    cur.execute(

        """CREATE TABLE IF NOT EXISTS parking_slots (

                id INTEGER PRIMARY KEY,

                slot_number TEXT UNIQUE,

                status TEXT

            )"""

    )


    # Initialize 10 slots if not exist

    cur.execute("SELECT COUNT(*) FROM parking_slots")

    count = cur.fetchone()[0]

    if count == 0:

        for i in range(1, 11):

            cur.execute("INSERT INTO parking_slots (slot_number, status) VALUES (?, ?)",

                        (f"SLOT-{i}", "Free"))

    conn.commit()

    conn.close()


# -----------------------

# Database Functions

# -----------------------

def get_slots():

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

    cur = conn.cursor()

    cur.execute("SELECT * FROM parking_slots")

    slots = cur.fetchall()

    conn.close()

    return slots


def update_slot(slot_id, status):

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

    cur = conn.cursor()

    cur.execute("UPDATE parking_slots SET status=? WHERE id=?", (status, slot_id))

    conn.commit()

    conn.close()


# -----------------------

# GUI Functions

# -----------------------

def refresh_slots():

    for widget in frame_slots.winfo_children():

        widget.destroy()


    slots = get_slots()

    for slot in slots:

        slot_id, slot_number, status = slot

        color = "green" if status == "Free" else "red"

        btn = tk.Button(frame_slots, text=f"{slot_number}\n{status}",

                        bg=color, fg="white", width=12, height=3,

                        command=lambda s=slot: toggle_slot(s))

        btn.pack(side=tk.LEFT, padx=5, pady=5)


def toggle_slot(slot):

    slot_id, slot_number, status = slot

    if status == "Free":

        update_slot(slot_id, "Booked")

        messagebox.showinfo("Booked", f"You booked {slot_number}")

    else:

        update_slot(slot_id, "Free")

        messagebox.showinfo("Freed", f"You freed {slot_number}")

    refresh_slots()


def random_update():

    slots = get_slots()

    random_slot = random.choice(slots)

    slot_id, slot_number, status = random_slot

    new_status = "Free" if status == "Booked" else "Booked"

    update_slot(slot_id, new_status)

    refresh_slots()

    root.after(5000, random_update)  # auto change every 5s


# -----------------------

# Main App

# -----------------------

if __name__ == "__main__":

    init_db()


    root = tk.Tk()

    root.title("Smart Parking System Simulator")

    root.geometry("800x400")


    tk.Label(root, text="šŸš— Smart Parking System Simulator", font=("Arial", 16, "bold")).pack(pady=10)


    frame_slots = tk.Frame(root)

    frame_slots.pack(pady=20)


    refresh_slots()


    # Auto slot updates (simulate cars parking)

    root.after(5000, random_update)


    root.mainloop()


AI Stock Predictor (Demo)

*An AI Stock Predictor (Demo) is a project to showcase ML + finance, while keeping it clear it’s for educational purposes only.

import yfinance as yf

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split

from sklearn.linear_model import LinearRegression

from sklearn.metrics import mean_squared_error


# -------------------------

# 1. Fetch Stock Data

# -------------------------

def get_stock_data(ticker="AAPL", period="1y"):

    data = yf.download(ticker, period=period)

    return data


# -------------------------

# 2. Feature Engineering

# -------------------------

def prepare_data(data):

    data["Prediction"] = data["Close"].shift(-30)  # predict 30 days ahead

    X = np.array(data[["Close"]])

    X = X[:-30]

    y = np.array(data["Prediction"])

    y = y[:-30]

    return X, y


# -------------------------

# 3. Train Model

# -------------------------

def train_model(X, y):

    X_train, X_test, y_train, y_test = train_test_split(

        X, y, test_size=0.2, random_state=42

    )

    model = LinearRegression()

    model.fit(X_train, y_train)

    preds = model.predict(X_test)

    mse = mean_squared_error(y_test, preds)

    return model, mse, X_test, y_test, preds


# -------------------------

# 4. Forecast Future Prices

# -------------------------

def forecast(model, data):

    X_forecast = np.array(data[["Close"]])[-30:]

    forecast_pred = model.predict(X_forecast)

    return forecast_pred


# -------------------------

# 5. Visualize Results

# -------------------------

def plot_results(data, forecast_pred):

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

    data["Close"].plot(label="Actual Close Price")

    forecast_index = range(len(data), len(data) + 30)

    plt.plot(forecast_index, forecast_pred, label="Predicted Next 30 Days", color="red")

    plt.legend()

    plt.title("AI Stock Price Predictor (Demo)")

    plt.xlabel("Days")

    plt.ylabel("Price (USD)")

    plt.show()


# -------------------------

# Main

# -------------------------

if __name__ == "__main__":

    ticker = input("Enter stock ticker (default AAPL): ") or "AAPL"

    data = get_stock_data(ticker)

    print(data.tail())


    X, y = prepare_data(data)

    model, mse, X_test, y_test, preds = train_model(X, y)


    print(f" Model trained with MSE: {mse:.2f}")


    forecast_pred = forecast(model, data)


    plot_results(data, forecast_pred)


Automatic Meeting Notes Generator

import speech_recognition as sr

from transformers import pipeline

from fpdf import FPDF


# -------------------------

# 1. Record or load audio

# -------------------------

def transcribe_audio(audio_file=None, duration=30):

    recognizer = sr.Recognizer()

    if audio_file:

        with sr.AudioFile(audio_file) as source:

            audio = recognizer.record(source)

    else:

        with sr.Microphone() as source:

            print("šŸŽ™️ Recording meeting... Speak now.")

            audio = recognizer.listen(source, phrase_time_limit=duration)

    

    try:

        print("šŸ”Ž Transcribing...")

        return recognizer.recognize_google(audio)

    except sr.UnknownValueError:

        return "Could not understand audio."

    except sr.RequestError:

        return "API unavailable."


# -------------------------

# 2. Summarize transcript

# -------------------------

def summarize_text(text):

    summarizer = pipeline("summarization", model="facebook/bart-large-cnn")

    summary = summarizer(text, max_length=150, min_length=50, do_sample=False)

    return summary[0]['summary_text']


# -------------------------

# 3. Save notes to PDF

# -------------------------

def save_to_pdf(transcript, summary, filename="meeting_notes.pdf"):

    pdf = FPDF()

    pdf.add_page()

    pdf.set_font("Arial", size=12)


    pdf.multi_cell(0, 10, " Meeting Transcript:\n" + transcript + "\n\n")

    pdf.multi_cell(0, 10, " Meeting Summary:\n" + summary)


    pdf.output(filename)

    print(f"✅ Notes saved as {filename}")


# -------------------------

# Main

# -------------------------

if __name__ == "__main__":

    # Record live OR use existing audio file (WAV recommended)

    transcript = transcribe_audio(audio_file=None, duration=20)

    print("\n Transcript:\n", transcript)


    if transcript and len(transcript) > 50:

        summary = summarize_text(transcript)

        print("\n Summary:\n", summary)

        save_to_pdf(transcript, summary)

    else:

        print(" Transcript too short to summarize.")


AI-Based Recipe Generator

import requests

import pandas as pd

import openai


#  Replace with your API keys

SPOONACULAR_API_KEY = "your_spoonacular_api_key"

OPENAI_API_KEY = "your_openai_api_key"


openai.api_key = OPENAI_API_KEY


# -----------------------------------

# 1. Get recipes from Spoonacular API

# -----------------------------------

def get_recipes_from_spoonacular(ingredients, number=5):

    url = f"https://api.spoonacular.com/recipes/findByIngredients"

    params = {

        "ingredients": ingredients,

        "number": number,

        "apiKey": SPOONACULAR_API_KEY

    }

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

    if response.status_code == 200:

        return response.json()

    else:

        print("❌ Error:", response.json())

        return []


# -----------------------------------

# 2. Get detailed nutritional info

# -----------------------------------

def get_recipe_nutrition(recipe_id):

    url = f"https://api.spoonacular.com/recipes/{recipe_id}/nutritionWidget.json"

    params = {"apiKey": SPOONACULAR_API_KEY}

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

    if response.status_code == 200:

        return response.json()

    return {}


# -----------------------------------

# 3. Use OpenAI to generate recipe idea

# -----------------------------------

def generate_ai_recipe(ingredients):

    prompt = f"Suggest a creative recipe using these ingredients: {ingredients}. Include steps and a short description."

    

    response = openai.Completion.create(

        engine="text-davinci-003",

        prompt=prompt,

        max_tokens=300,

        temperature=0.7

    )

    return response.choices[0].text.strip()


# -----------------------------------

# Example Run

# -----------------------------------

if __name__ == "__main__":

    user_ingredients = input("Enter ingredients (comma separated): ")

    

    print("\nšŸ² Fetching recipe ideas from Spoonacular...\n")

    recipes = get_recipes_from_spoonacular(user_ingredients)

    

    recipe_list = []

    for r in recipes:

        nutrition = get_recipe_nutrition(r["id"])

        recipe_list.append({

            "Title": r["title"],

            "Used Ingredients": len(r["usedIngredients"]),

            "Missed Ingredients": len(r["missedIngredients"]),

            "Calories": nutrition.get("calories", "N/A"),

            "Carbs": nutrition.get("carbs", "N/A"),

            "Protein": nutrition.get("protein", "N/A"),

            "Fat": nutrition.get("fat", "N/A")

        })

    

    df = pd.DataFrame(recipe_list)

    print(df)

    

    print("\nšŸ¤– AI Suggested Recipe:\n")

    ai_recipe = generate_ai_recipe(user_ingredients)

    print(ai_recipe)