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)


Smart Resume Formatter

from docx import Document

from docx.shared import Pt

from fpdf import FPDF


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

# 1. Format Resume into Word

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

def create_word_resume(data, filename="resume.docx"):

    doc = Document()

    

    # Title (Name)

    title = doc.add_paragraph(data["name"])

    title.style = doc.styles['Title']

    

    # Contact Info

    doc.add_paragraph(f'Email: {data["email"]} | Phone: {data["phone"]}')

    

    # Sections

    doc.add_heading('Summary', level=1)

    doc.add_paragraph(data["summary"])

    

    doc.add_heading('Experience', level=1)

    for job in data["experience"]:

        doc.add_paragraph(f"{job['role']} at {job['company']} ({job['years']})")

        doc.add_paragraph(job["details"], style="List Bullet")

    

    doc.add_heading('Education', level=1)

    for edu in data["education"]:

        doc.add_paragraph(f"{edu['degree']} - {edu['institution']} ({edu['year']})")

    

    doc.add_heading('Skills', level=1)

    doc.add_paragraph(", ".join(data["skills"]))

    

    doc.save(filename)

    print(f"✅ Word Resume saved as {filename}")



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

# 2. Format Resume into PDF

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

def create_pdf_resume(data, filename="resume.pdf"):

    pdf = FPDF()

    pdf.add_page()

    pdf.set_font("Arial", 'B', 16)

    

    # Title (Name)

    pdf.cell(200, 10, data["name"], ln=True, align="C")

    

    pdf.set_font("Arial", '', 12)

    pdf.cell(200, 10, f'Email: {data["email"]} | Phone: {data["phone"]}', ln=True, align="C")

    

    # Sections

    pdf.set_font("Arial", 'B', 14)

    pdf.cell(200, 10, "Summary", ln=True)

    pdf.set_font("Arial", '', 12)

    pdf.multi_cell(0, 10, data["summary"])

    

    pdf.set_font("Arial", 'B', 14)

    pdf.cell(200, 10, "Experience", ln=True)

    pdf.set_font("Arial", '', 12)

    for job in data["experience"]:

        pdf.multi_cell(0, 10, f"{job['role']} at {job['company']} ({job['years']})\n - {job['details']}")

    

    pdf.set_font("Arial", 'B', 14)

    pdf.cell(200, 10, "Education", ln=True)

    pdf.set_font("Arial", '', 12)

    for edu in data["education"]:

        pdf.cell(200, 10, f"{edu['degree']} - {edu['institution']} ({edu['year']})", ln=True)

    

    pdf.set_font("Arial", 'B', 14)

    pdf.cell(200, 10, "Skills", ln=True)

    pdf.set_font("Arial", '', 12)

    pdf.multi_cell(0, 10, ", ".join(data["skills"]))

    

    pdf.output(filename)

    print(f"✅ PDF Resume saved as {filename}")



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

# Example Data

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

resume_data = {

    "name": "John Doe",

    "email": "john.doe@email.com",

    "phone": "+1-234-567-890",

    "summary": "Passionate software engineer with 5+ years of experience in building scalable applications.",

    "experience": [

        {"role": "Backend Developer", "company": "TechCorp", "years": "2020-2023", "details": "Developed APIs and microservices using Python & Django."},

        {"role": "Software Engineer", "company": "CodeWorks", "years": "2017-2020", "details": "Worked on automation tools and optimized system performance."}

    ],

    "education": [

        {"degree": "B.Sc. Computer Science", "institution": "XYZ University", "year": "2017"}

    ],

    "skills": ["Python", "Django", "Flask", "SQL", "Docker", "AWS"]

}


# Run both functions

create_word_resume(resume_data)

create_pdf_resume(resume_data)


AI Workout Form Corrector

import cv2

import mediapipe as mp

import numpy as np


mp_drawing = mp.solutions.drawing_utils

mp_pose = mp.solutions.pose


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

# Calculate angle between 3 points

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

def calculate_angle(a, b, c):

    a = np.array(a)  # First

    b = np.array(b)  # Mid

    c = np.array(c)  # End

    

    radians = np.arctan2(c[1]-b[1], c[0]-b[0]) - np.arctan2(a[1]-b[1], a[0]-b[0])

    angle = np.abs(radians*180.0/np.pi)

    

    if angle > 180.0:

        angle = 360 - angle

    return angle


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

# Main workout tracker (Squats Example)

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

cap = cv2.VideoCapture(0)


with mp_pose.Pose(min_detection_confidence=0.7, min_tracking_confidence=0.7) as pose:

    counter = 0

    stage = None

    

    while cap.isOpened():

        ret, frame = cap.read()

        if not ret:

            break

        

        # Recolor image

        image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

        image.flags.writeable = False

        

        # Make detection

        results = pose.process(image)

        

        # Recolor back to BGR

        image.flags.writeable = True

        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

        

        try:

            landmarks = results.pose_landmarks.landmark

            

            # Get coordinates

            hip = [landmarks[mp_pose.PoseLandmark.LEFT_HIP.value].x,

                   landmarks[mp_pose.PoseLandmark.LEFT_HIP.value].y]

            knee = [landmarks[mp_pose.PoseLandmark.LEFT_KNEE.value].x,

                    landmarks[mp_pose.PoseLandmark.LEFT_KNEE.value].y]

            ankle = [landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value].x,

                     landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value].y]

            

            # Calculate angle

            angle = calculate_angle(hip, knee, ankle)

            

            # Visualize angle

            cv2.putText(image, str(int(angle)),

                        tuple(np.multiply(knee, [640, 480]).astype(int)),

                        cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA

                        )

            

            # Squat counter logic

            if angle > 160:

                stage = "up"

            if angle < 90 and stage == "up":

                stage = "down"

                counter += 1

                print(f"✅ Squat count: {counter}")

            

            # Feedback

            if angle < 70:

                feedback = "Too Low! Go Higher"

            elif 70 <= angle <= 100:

                feedback = "Perfect Depth ✅"

            else:

                feedback = "Stand Tall"

            

            cv2.putText(image, feedback, (50,100),

                        cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), 2, cv2.LINE_AA)

            

        except:

            pass

        

        # Render detections

        mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_pose.POSE_CONNECTIONS,

                                  mp_drawing.DrawingSpec(color=(245,117,66), thickness=2, circle_radius=2),

                                  mp_drawing.DrawingSpec(color=(245,66,230), thickness=2, circle_radius=2)

                                 )               

        

        cv2.imshow('AI Workout Form Corrector - Squats', image)

        

        if cv2.waitKey(10) & 0xFF == ord('q'):

            break

    

    cap.release()

    cv2.destroyAllWindows()