20 Python Project Ideas for College Students (with source code)

Whether you are looking to brush up your skills in Python or crack a top IT job, here are 20 advanced Python projects you can work on. Read the complete article to find exciting Python project ideas for college students.

20 Python Project Ideas for College Students (with source code)

Introduction

If you have been tirelessly searching for Python project ideas for college students, you have just landed at the right spot! Whether you are just starting college or in your final year, we understand the cruciality of having an impressive portfolio.

That's why, in this blog, we will provide you with advanced Python project ideas and include the source code for your ease.

In the ever-evolving tech landscape, Python remains a cornerstone of innovation, powering applications in data science, machine learning, web development, and beyond.

However, not all projects carry equal weight in showcasing your expertise. While basic projects like a "To-Do List" app or a "Simple Calculator" are good starting points, they do little to impress employers in a competitive job market.

What truly makes a difference is working on intermediate to advanced Python projects that solve real-world problems and highlight your technical versatility.

This blog will take you through over 20 project ideas beyond the basics. Whether you’re interested in artificial intelligence, web development, automation, or cybersecurity, these projects are tailored to help you build a portfolio that stands out to recruiters.

Let’s dive in and explore Python projects that can elevate your skills and prepare you for a rewarding tech career.


Building Advanced Web Applications with Django & Flask

Web development is a popular domain for Python enthusiasts, thanks to frameworks like Django and Flask. Building dynamic web applications allows you to showcase your ability to design, develop, and deploy user-centric solutions.


1. Customized Learning Management System (LMS)

Unlike basic CRUD (Create, Read, Update, Delete) apps, this project would require implementing features like role-based authentication, interactive dashboards, assignment submissions, and performance analytics.

By integrating APIs for video conferencing and real-time chat, you can further enhance the functionality of the LMS.

Additionally, deploying this project on cloud platforms like AWS or Heroku will display your deployment expertise, a skill valued by employers.


Source code

### Learning Management System (LMS) - Source Code

# Setting up the Django LMS Project
# This code provides an overview of building a basic LMS with role-based authentication, user dashboards, and assignment handling.

# Step 1: Create a Django Project
# Command: django-admin startproject lms_project

# Step 2: Create an LMS App
# Command: python manage.py startapp lms

# Step 3: Install Required Libraries
# Install Django and required dependencies using pip:
# pip install django djangorestframework

# Step 4: Define Models in the LMS App
from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    ROLE_CHOICES = [
        ('student', 'Student'),
        ('teacher', 'Teacher'),
        ('admin', 'Admin'),
    ]
    role = models.CharField(max_length=10, choices=ROLE_CHOICES, default='student')

class Course(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()
    teacher = models.ForeignKey(User, on_delete=models.CASCADE, related_name='courses', limit_choices_to={'role': 'teacher'})

class Assignment(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='assignments')
    due_date = models.DateTimeField()

class Submission(models.Model):
    assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE, related_name='submissions')
    student = models.ForeignKey(User, on_delete=models.CASCADE, related_name='submissions', limit_choices_to={'role': 'student'})
    file = models.FileField(upload_to='submissions/')
    submitted_at = models.DateTimeField(auto_now_add=True)

# Step 5: Create Serializers for the API (if required)
from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'role']

class CourseSerializer(serializers.ModelSerializer):
    class Meta:
        model = Course
        fields = ['id', 'name', 'description', 'teacher']

class AssignmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Assignment
        fields = ['id', 'title', 'description', 'course', 'due_date']

class SubmissionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Submission
        fields = ['id', 'assignment', 'student', 'file', 'submitted_at']

# Step 6: Add Views for Handling Data and API Requests
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from .models import Course, Assignment, Submission
from .serializers import CourseSerializer, AssignmentSerializer, SubmissionSerializer

class CourseListView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        courses = Course.objects.filter(teacher=request.user) if request.user.role == 'teacher' else Course.objects.all()
        serializer = CourseSerializer(courses, many=True)
        return Response(serializer.data)

class AssignmentListView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request, course_id):
        assignments = Assignment.objects.filter(course_id=course_id)
        serializer = AssignmentSerializer(assignments, many=True)
        return Response(serializer.data)

# Step 7: Create Templates and Static Files
# Use Django Templates to create interactive pages for teachers, students, and admins.
# Example: Create a dashboard.html file for displaying course details and assignments.

# Step 8: Update URLs
from django.urls import path
from .views import CourseListView, AssignmentListView

urlpatterns = [
    path('courses/', CourseListView.as_view(), name='course-list'),
    path('courses/<int:course_id>/assignments/', AssignmentListView.as_view(), name='assignment-list'),
]

# Step 9: Run Migrations
# Command: python manage.py makemigrations
# Command: python manage.py migrate

# Step 10: Run the Server
# Command: python manage.py runserver

# Step 11: Deploy the Project
# Use platforms like AWS, Heroku, or PythonAnywhere to deploy the LMS and make it accessible online.

2. Job Portal Application

With Python and Django, you can implement AI-based job recommendations, resume parsing, and real-time notifications.

This project will also allow you to explore integrations with external APIs like LinkedIn or GitHub, adding a layer of professionalism to your work.


Source code

import os
from flask import Flask, render_template, request, redirect, url_for, session, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
from sqlalchemy.dialects.postgresql import JSON
import datetime

# Initialize Flask app and configurations
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///job_portal.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'secretkey'

# Initialize extensions
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)
login_manager.login_view = 'login'

# Models
class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(150), nullable=False, unique=True)
    email = db.Column(db.String(150), nullable=False, unique=True)
    password = db.Column(db.String(150), nullable=False)
    role = db.Column(db.String(50), nullable=False, default='candidate')  # "candidate" or "employer"

class Job(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(150), nullable=False)
    description = db.Column(db.Text, nullable=False)
    company = db.Column(db.String(150), nullable=False)
    location = db.Column(db.String(150), nullable=False)
    salary = db.Column(db.Integer, nullable=True)
    date_posted = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    requirements = db.Column(db.Text, nullable=False)
    posted_by = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

# Routes
@app.route('/')
def home():
    jobs = Job.query.order_by(Job.date_posted.desc()).all()
    return render_template('home.html', jobs=jobs)

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        email = request.form['email']
        password = bcrypt.generate_password_hash(request.form['password']).decode('utf-8')
        role = request.form['role']
        
        if User.query.filter_by(email=email).first():
            return 'Email already exists!'
        
        new_user = User(username=username, email=email, password=password, role=role)
        db.session.add(new_user)
        db.session.commit()
        return redirect(url_for('login'))

    return render_template('register.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        email = request.form['email']
        password = request.form['password']
        user = User.query.filter_by(email=email).first()

        if user and bcrypt.check_password_hash(user.password, password):
            login_user(user)
            return redirect(url_for('home'))
        return 'Invalid credentials!'

    return render_template('login.html')

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('login'))

@app.route('/post_job', methods=['GET', 'POST'])
@login_required
def post_job():
    if current_user.role != 'employer':
        return 'Access denied!'

    if request.method == 'POST':
        title = request.form['title']
        description = request.form['description']
        company = request.form['company']
        location = request.form['location']
        salary = request.form['salary']
        requirements = request.form['requirements']
        
        new_job = Job(title=title, description=description, company=company, location=location, salary=salary, requirements=requirements, posted_by=current_user.id)
        db.session.add(new_job)
        db.session.commit()
        return redirect(url_for('home'))

    return render_template('post_job.html')

@app.route('/job/<int:job_id>')
def job_detail(job_id):
    job = Job.query.get_or_404(job_id)
    return render_template('job_detail.html', job=job)

@app.route('/apply/<int:job_id>', methods=['POST'])
@login_required
def apply(job_id):
    job = Job.query.get_or_404(job_id)
    # Logic to handle applications can be extended here
    return jsonify({"message": "Application submitted successfully!"})

# Run server
if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)

Data Science Projects

Data science remains one of the most lucrative fields in the tech industry, and Python is its lifeblood. To stand out, focus on projects beyond basic data analysis and visualization.

This will showcase your ability to work with time-series data, machine learning models, and visualization libraries like Matplotlib and Seaborn.

This project would involve gathering real-time stock data using APIs, cleaning and preprocessing the data, and applying algorithms like ARIMA or LSTM to predict future stock prices.

Presenting the results in an interactive dashboard using tools like Plotly or Dash can further elevate your project.

Source code

### Predictive Analytics Tool for Stock Market Trends

# Import necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
import yfinance as yf

# Step 1: Fetch Stock Market Data
def fetch_stock_data(ticker, start_date, end_date):
    data = yf.download(ticker, start=start_date, end=end_date)
    data['Date'] = data.index
    data = data[['Date', 'Close']]
    return data

# Step 2: Prepare Data for Model
def prepare_data(data, time_step=60):
    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1, 1))

    x_train, y_train = [], []
    for i in range(time_step, len(scaled_data)):
        x_train.append(scaled_data[i-time_step:i, 0])
        y_train.append(scaled_data[i, 0])
    
    x_train, y_train = np.array(x_train), np.array(y_train)
    x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))

    return x_train, y_train, scaler

# Step 3: Build the LSTM Model
def build_lstm_model():
    model = Sequential()
    model.add(LSTM(units=50, return_sequences=True, input_shape=(60, 1)))
    model.add(LSTM(units=50, return_sequences=False))
    model.add(Dense(units=25))
    model.add(Dense(units=1))

    model.compile(optimizer='adam', loss='mean_squared_error')
    return model

# Step 4: Train and Evaluate the Model
def train_model(model, x_train, y_train, epochs=5, batch_size=32):
    model.fit(x_train, y_train, epochs=epochs, batch_size=batch_size)
    return model

# Step 5: Predict Future Trends
def predict_trends(model, data, scaler, time_step=60):
    last_60_days = data['Close'].values[-time_step:]
    last_60_days_scaled = scaler.transform(last_60_days.reshape(-1, 1))
    x_test = []
    x_test.append(last_60_days_scaled)
    x_test = np.array(x_test)
    x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))

    predicted_price = model.predict(x_test)
    predicted_price = scaler.inverse_transform(predicted_price)
    return predicted_price

# Step 6: Visualization
def plot_predictions(actual, predicted):
    plt.figure(figsize=(12, 6))
    plt.plot(actual, color='blue', label='Actual Prices')
    plt.plot(predicted, color='red', label='Predicted Prices')
    plt.title('Stock Market Price Prediction')
    plt.xlabel('Time')
    plt.ylabel('Stock Price')
    plt.legend()
    plt.show()

# Main Execution
if __name__ == "__main__":
    # User Inputs
    ticker = 'AAPL'  # Replace with the stock ticker you want to analyze
    start_date = '2020-01-01'
    end_date = '2023-01-01'

    # Fetch and prepare data
    stock_data = fetch_stock_data(ticker, start_date, end_date)
    x_train, y_train, scaler = prepare_data(stock_data)

    # Build and train the model
    lstm_model = build_lstm_model()
    lstm_model = train_model(lstm_model, x_train, y_train)

    # Predict future trends
    predicted_price = predict_trends(lstm_model, stock_data, scaler)
    print(f"Predicted Stock Price: {predicted_price[0][0]}")

    # Visualize the predictions (using past data for comparison if available)
    # plot_predictions(stock_data['Close'].values, predicted_price)

4. Personalized recommendation systems for e-commerce platforms

Unlike basic recommendation systems, this project can incorporate collaborative filtering, content-based filtering, and deep learning algorithms to provide highly accurate suggestions.

By using libraries like Scikit-learn, TensorFlow, and Pandas, you can demonstrate your expertise in machine learning and data manipulation.

Hosting this project on GitHub with a detailed README file and deployment instructions will make it an excellent addition to your portfolio.

Source code

### Project: Personalized Recommendation System for E-Commerce Platforms

import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from surprise import SVD
from surprise import Dataset, Reader
from surprise.model_selection import cross_validate

# Load Dataset
data = pd.read_csv("ecommerce_data.csv")

# Sample Data Structure
# data = pd.DataFrame({
#     'user_id': [1, 2, 3, ...],
#     'item_id': [101, 102, 103, ...],
#     'rating': [4.0, 5.0, 3.0, ...],
#     'description': ["A great gadget for tech enthusiasts.", "Perfect for everyday use.", ...]
# })

# Text-Based Recommendation (Content-Based Filtering)
# Use product descriptions to create a TF-IDF matrix
tfidf = TfidfVectorizer(stop_words='english')
data['description'] = data['description'].fillna('')  # Handle missing descriptions
tfidf_matrix = tfidf.fit_transform(data['description'])

# Compute cosine similarity between items
cosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)

# Function to generate recommendations based on content similarity
def get_content_recommendations(item_id, cosine_sim=cosine_sim, top_n=5):
    idx = data[data['item_id'] == item_id].index[0]
    sim_scores = list(enumerate(cosine_sim[idx]))
    sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
    sim_scores = sim_scores[1:top_n+1]  # Skip the first item as it’s the same product
    item_indices = [i[0] for i in sim_scores]
    return data.iloc[item_indices][['item_id', 'description']]

# Example Content-Based Recommendation
print("Content-Based Recommendations:")
print(get_content_recommendations(101))

# Collaborative Filtering with Surprise Library
# Preparing the data for collaborative filtering
reader = Reader(rating_scale=(1, 5))
data_surprise = Dataset.load_from_df(data[['user_id', 'item_id', 'rating']], reader)

# Splitting the dataset
trainset, testset = train_test_split(data[['user_id', 'item_id', 'rating']], test_size=0.2, random_state=42)

# Apply SVD (Singular Value Decomposition)
model = SVD()
cross_validate(model, data_surprise, cv=5, verbose=True)

# Train and Predict
trainset_surprise = data_surprise.build_full_trainset()
model.fit(trainset_surprise)

# Function to generate collaborative filtering recommendations
def get_collab_recommendations(user_id, model=model, top_n=5):
    user_items = data[data['user_id'] == user_id]['item_id'].tolist()
    predictions = [
        (iid, model.predict(user_id, iid).est)
        for iid in data['item_id'].unique()
        if iid not in user_items
    ]
    predictions = sorted(predictions, key=lambda x: x[1], reverse=True)[:top_n]
    return pd.DataFrame(predictions, columns=['item_id', 'predicted_rating'])

# Example Collaborative Filtering Recommendation
print("Collaborative Filtering Recommendations:")
print(get_collab_recommendations(2))

# Hybrid Recommendation System
# Combine Content-Based and Collaborative Filtering

def hybrid_recommendations(user_id, item_id, alpha=0.5):
    # alpha: weight for content-based vs collaborative filtering
    content_recs = get_content_recommendations(item_id, top_n=10)
    collab_recs = get_collab_recommendations(user_id, top_n=10)

    # Merge the results with weighted averaging
    merged = pd.merge(
        content_recs,
        collab_recs,
        on='item_id',
        how='outer',
        suffixes=('_content', '_collab')
    )
    merged['score'] = merged['predicted_rating'] * alpha + merged.index * (1 - alpha)
    return merged.sort_values(by='score', ascending=False)

# Example Hybrid Recommendation
print("Hybrid Recommendations:")
print(hybrid_recommendations(2, 101))

Implementing Machine & Deep Learning models

Machine learning (ML) and deep learning (DL) are at the forefront of technological innovation, and having practical experience in this domain is a significant advantage.

5. Real-Time Facial Recognition System

This project would use libraries like OpenCV and TensorFlow to build a system to identify and authenticate users based on their facial features.

To add a layer of sophistication, you can implement features like emotion detection or age estimation, showcasing your ability to work with convolutional neural networks (CNNs).

Source code

# Real-Time Facial Recognition System

import cv2
import numpy as np
from keras.models import load_model
from keras.preprocessing.image import img_to_array

# Load pre-trained face detection model
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

# Load pre-trained facial recognition model
model = load_model('facial_recognition_model.h5')

# Define emotion labels (example: emotions for demonstration)
emotion_labels = ['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']

def preprocess_face(face):
    face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)  # Convert to grayscale
    face = cv2.resize(face, (48, 48))  # Resize to model input size
    face = face / 255.0  # Normalize pixel values
    face = img_to_array(face)
    face = np.expand_dims(face, axis=0)
    return face

def recognize_face(face):
    predictions = model.predict(face)[0]
    emotion_index = np.argmax(predictions)
    return emotion_labels[emotion_index], predictions[emotion_index]

def main():
    cap = cv2.VideoCapture(0)
    print("[INFO] Starting webcam for real-time facial recognition...")

    while True:
        ret, frame = cap.read()
        if not ret:
            print("[ERROR] Unable to access webcam.")
            break

        gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray_frame, scaleFactor=1.3, minNeighbors=5, minSize=(30, 30))

        for (x, y, w, h) in faces:
            face = frame[y:y + h, x:x + w]
            preprocessed_face = preprocess_face(face)

            emotion, confidence = recognize_face(preprocessed_face)

            label = f"{emotion} ({confidence * 100:.2f}%)"
            cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
            cv2.putText(frame, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)

        cv2.imshow("Real-Time Facial Recognition", frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            print("[INFO] Quitting program.")
            break

    cap.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()

6. Fraud Detection System for Financial Transactions

This project would require you to work with large datasets, preprocess the data, and train machine learning models to identify fraudulent patterns.

By implementing advanced techniques like feature engineering, ensemble learning, and anomaly detection, you can showcase your ability to solve complex problems.

Using Flask or Django to create an API for real-time fraud detection can further demonstrate your end-to-end development skills.

Source code

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report
import pickle
from flask import Flask, request, jsonify

# Load and preprocess the dataset
def load_data():
    # Replace 'transactions.csv' with your dataset file
    data = pd.read_csv("transactions.csv")
    
    # Example: Ensure necessary preprocessing is performed (e.g., encoding categorical variables)
    data = pd.get_dummies(data, drop_first=True)  # Convert categorical variables to numerical
    X = data.drop(columns=["is_fraud"])  # Feature set (excluding target variable)
    y = data["is_fraud"]                # Target variable
    
    return X, y

# Train and save the model
def train_model():
    X, y = load_data()
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
    
    # Train a Random Forest model
    model = RandomForestClassifier(n_estimators=100, random_state=42)
    model.fit(X_train, y_train)
    
    # Evaluate model performance
    y_pred = model.predict(X_test)
    print("Accuracy:", accuracy_score(y_test, y_pred))
    print("Classification Report:\n", classification_report(y_test, y_pred))
    
    # Save the trained model to a file
    with open("fraud_detection_model.pkl", "wb") as file:
        pickle.dump(model, file)

# Flask API for real-time fraud detection
app = Flask(__name__)

@app.route('/predict', methods=['POST'])
def predict():
    # Load the trained model
    with open("fraud_detection_model.pkl", "rb") as file:
        model = pickle.load(file)
    
    # Parse input data from the request
    input_data = request.json  # Assuming the input is sent as JSON
    features = pd.DataFrame([input_data])  # Convert input to DataFrame
    
    # Perform prediction
    prediction = model.predict(features)
    response = {"is_fraud": bool(prediction[0])}  # Convert 0/1 to True/False
    return jsonify(response)

if __name__ == "__main__":
    # Uncomment the line below to train the model (only needed once)
    # train_model()
    
    # Run the Flask app
    app.run(debug=True)

Venture into Natural Language Processing (NLP)

Natural Language Processing is an exciting field with applications ranging from chatbots to sentiment analysis.

7. Multi-lingual chatbot for customer support

This project would involve training NLP models to understand and respond to queries in multiple languages. Using libraries like SpaCy and Hugging Face Transformers, you can create a chatbot capable of handling complex queries.

Deploying the chatbot on messaging platforms like WhatsApp or Slack via APIs will further showcase your technical expertise.

Source code

import random
from flask import Flask, request, jsonify
from transformers import pipeline

# Load pre-trained NLP models for multiple languages
english_bot = pipeline("text-generation", model="microsoft/DialoGPT-medium")
spanish_bot = pipeline("text-generation", model="microsoft/DialoGPT-medium")

# Language selection helper
def get_bot_response(language, user_input):
    if language == "english":
        response = english_bot(user_input, max_length=50, pad_token_id=50256)
    elif language == "spanish":
        response = spanish_bot(user_input, max_length=50, pad_token_id=50256)
    else:
        response = [{"generated_text": "Sorry, language not supported!"}]
    return response[0]["generated_text"]

# Flask app
app = Flask(__name__)

@app.route("/chat", methods=["POST"])
def chat():
    data = request.json
    language = data.get("language", "english").lower()
    user_input = data.get("user_input", "")

    if not user_input:
        return jsonify({"response": "Please provide a valid user input."})

    bot_response = get_bot_response(language, user_input)
    return jsonify({"response": bot_response})

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

Legal professionals often deal with lengthy documents; a tool that can summarize these texts accurately would be invaluable.

This project would require you to work with pre-trained transformer models like BERT or GPT-3 and fine-tune them for summarization tasks.

By integrating the tool into a web or desktop application, you can make it user-friendly and practical.

Source code

# Import required libraries
from flask import Flask, render_template, request, jsonify
from transformers import pipeline

# Initialize Flask App
app = Flask(__name__)

# Load the pre-trained summarization model
print("Loading the Text Summarization Model... Please wait!")
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
print("Model loaded successfully!")

# Home Route
@app.route('/')
def index():
    return render_template('index.html')

# API Route to Summarize Text
@app.route('/summarize', methods=['POST'])
def summarize():
    try:
        # Extract the text from user input
        data = request.get_json()
        input_text = data['text']

        # Check if text is empty
        if not input_text.strip():
            return jsonify({"error": "Input text cannot be empty!"}), 400

        # Generate the summary
        summary = summarizer(input_text, max_length=150, min_length=40, do_sample=False)
        summary_text = summary[0]['summary_text']

        # Return the summary as JSON
        return jsonify({"summary": summary_text})

    except Exception as e:
        return jsonify({"error": str(e)}), 500

# Run Flask App
if __name__ == "__main__":
    app.run(debug=True)

Automation Systems

Automation is a key skill for tech professionals, and Python excels in this domain.

9. Smart Home Automation System

Using Raspberry Pi, Python, and IoT devices, you can create a system that allows users to control their home appliances via a mobile app or voice commands.

By integrating AI-based features like energy consumption analysis and predictive maintenance, you can take this project to the next level.

Source code

import time
import random
from flask import Flask, request, jsonify

app = Flask(__name__)

# Simulated Devices and States
devices = {
    "living_room_light": False,
    "bedroom_light": False,
    "ac_temperature": 24,
    "door_lock": False,
    "camera_status": False
}

# Simulate Device Control
def toggle_device(device):
    devices[device] = not devices[device]

def set_temperature(temp):
    devices["ac_temperature"] = temp

def random_motion_detection():
    return random.choice([True, False])

# Routes
@app.route('/')
def home():
    return "Welcome to the Smart Home Automation System!"

@app.route('/status', methods=['GET'])
def status():
    return jsonify(devices)

@app.route('/toggle/<device>', methods=['POST'])
def toggle(device):
    if device in devices:
        toggle_device(device)
        return jsonify({device: devices[device]})
    return jsonify({"error": "Device not found"}), 404

@app.route('/set_temperature', methods=['POST'])
def set_temp():
    data = request.get_json()
    temp = data.get("temperature", None)
    if temp and isinstance(temp, int):
        set_temperature(temp)
        return jsonify({"ac_temperature": devices["ac_temperature"]})
    return jsonify({"error": "Invalid temperature"}), 400

@app.route('/motion_detected', methods=['GET'])
def motion():
    motion_detected = random_motion_detection()
    return jsonify({"motion_detected": motion_detected})

@app.route('/camera/<status>', methods=['POST'])
def camera(status):
    if status.lower() in ['on', 'off']:
        devices['camera_status'] = True if status.lower() == 'on' else False
        return jsonify({"camera_status": devices["camera_status"]})
    return jsonify({"error": "Invalid status"}), 400

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

10. Web Scraping & Data Aggregation Tool

This project would involve scraping data from multiple websites, cleaning and structuring it, and presenting it in an interactive dashboard.

By using libraries like BeautifulSoup, Selenium, and Pandas, you can showcase your ability to automate complex workflows.

Source code

import requests
from bs4 import BeautifulSoup
import pandas as pd
import time

# Function to scrape data from a single URL
def scrape_data(url):
    try:
        response = requests.get(url)
        soup = BeautifulSoup(response.content, 'html.parser')

        # Example: Extracting article titles and links
        data = []
        articles = soup.find_all('h2', class_='entry-title')
        for article in articles:
            title = article.get_text()
            link = article.find('a')['href']
            data.append({"Title": title, "Link": link})
        return data
    except Exception as e:
        print(f"Error occurred: {e}")
        return []

# List of URLs to scrape
urls = [
    "https://example-blog.com/page/1",
    "https://example-blog.com/page/2",
    "https://example-blog.com/page/3",
]

# Aggregate data from multiple URLs
def aggregate_data(urls):
    aggregated_data = []
    for url in urls:
        print(f"Scraping: {url}")
        data = scrape_data(url)
        aggregated_data.extend(data)
        time.sleep(2)  # To prevent overloading the server
    return aggregated_data

# Save data to CSV
def save_to_csv(data, filename):
    if data:
        df = pd.DataFrame(data)
        df.to_csv(filename, index=False)
        print(f"Data saved to {filename}")
    else:
        print("No data to save.")

# Main function
if __name__ == "__main__":
    urls_to_scrape = urls  # Replace with target URLs
    scraped_data = aggregate_data(urls_to_scrape)
    save_to_csv(scraped_data, "scraped_articles.csv")
    print("Web scraping and aggregation complete!")

Exploring CyberSecurity

Cybersecurity is a critical area in which Python plays a significant role. From automating tasks to analyzing large data sets, Python's simplicity and flexibility are one of the core reasons behind the dependency on the language in cybersec.

11. Network Intrusion Detection System (NIDS)

This project would involve capturing network packets using libraries like Scapy, analyzing the data for suspicious activity, and alerting users in real-time.

By incorporating machine learning algorithms for anomaly detection, you can enhance the system’s accuracy and effectiveness.

Source code

from scapy.all import sniff, IP, TCP, UDP
import time

# Configuration
THRESHOLD = 10  # Number of packets per second that triggers an alert
DURATION = 10   # Monitor duration in seconds

# Dictionary to track IP addresses and packet counts
packet_counts = {}

# Function to process packets
def process_packet(packet):
    global packet_counts
    src_ip = None

    # Check for IP packets
    if IP in packet:
        src_ip = packet[IP].src

        # Update packet count
        if src_ip in packet_counts:
            packet_counts[src_ip] += 1
        else:
            packet_counts[src_ip] = 1

# Function to monitor traffic
def monitor_traffic(duration):
    global packet_counts
    packet_counts = {}
    print("Monitoring network traffic...")
    sniff(prn=process_packet, timeout=duration)
    print("Monitoring completed.\n")

# Function to analyze results and detect intrusions
def detect_intrusion():
    print("Analyzing traffic for potential intrusions...")
    intrusions = []

    for ip, count in packet_counts.items():
        if count > THRESHOLD:
            intrusions.append((ip, count))

    if intrusions:
        print("\nALERT: Intrusions detected!")
        for ip, count in intrusions:
            print(f"Suspicious IP: {ip} | Packets: {count}")
    else:
        print("No intrusions detected. Network is normal.")

# Main function
if __name__ == "__main__":
    print(f"Starting Network Intrusion Detection System (NIDS)...")
    print(f"Monitoring for {DURATION} seconds with a threshold of {THRESHOLD} packets per IP.\n")

    monitor_traffic(DURATION)
    detect_intrusion()

12. Password manager with end-to-end encryption

This project would require you to implement cryptographic techniques for secure data storage and retrieval.

By adding features like password strength analysis and two-factor authentication, you can demonstrate your ability to build secure applications.

Source code

from cryptography.fernet import Fernet
import os
import json

# Generate and save the encryption key
def generate_key():
    key = Fernet.generate_key()
    with open("key.key", "wb") as key_file:
        key_file.write(key)
    print("Encryption key generated and saved.")

# Load the encryption key
def load_key():
    if not os.path.exists("key.key"):
        raise FileNotFoundError("Key file not found! Generate a key first.")
    with open("key.key", "rb") as key_file:
        return key_file.read()

# Encrypt a password
def encrypt_password(password, key):
    f = Fernet(key)
    return f.encrypt(password.encode()).decode()

# Decrypt a password
def decrypt_password(encrypted_password, key):
    f = Fernet(key)
    return f.decrypt(encrypted_password.encode()).decode()

# Save passwords to a file
def save_passwords(data):
    with open("passwords.json", "w") as file:
        json.dump(data, file, indent=4)

# Load passwords from a file
def load_passwords():
    if not os.path.exists("passwords.json"):
        return {}
    with open("passwords.json", "r") as file:
        return json.load(file)

# Main application
def password_manager():
    key = load_key()
    passwords = load_passwords()

    while True:
        print("\n--- Password Manager ---")
        print("1. Add new password")
        print("2. View saved passwords")
        print("3. Exit")

        choice = input("Choose an option: ")

        if choice == "1":
            service = input("Enter the service name: ")
            username = input("Enter the username: ")
            password = input("Enter the password: ")
            encrypted_password = encrypt_password(password, key)
            passwords[service] = {"username": username, "password": encrypted_password}
            save_passwords(passwords)
            print("Password saved successfully!")

        elif choice == "2":
            for service, creds in passwords.items():
                decrypted_password = decrypt_password(creds['password'], key)
                print(f"Service: {service}, Username: {creds['username']}, Password: {decrypted_password}")

        elif choice == "3":
            print("Exiting Password Manager. Goodbye!")
            break

        else:
            print("Invalid choice. Please try again.")

# Entry point
if __name__ == "__main__":
    if not os.path.exists("key.key"):
        print("No encryption key found. Generating a new key...")
        generate_key()
    password_manager()

Game Development

While game development is not the most common application of Python, it’s a great way to showcase your creativity and problem-solving skills.

13. Multiplayer Online Game

This project would involve designing game mechanics, implementing a client-server architecture, and ensuring a seamless user experience.

You can make your game stand out by incorporating features like leaderboards, in-game purchases, and chat functionality.

Source code

import socket
import threading

# Server Code
class GameServer:
    def __init__(self, host="127.0.0.1", port=5555):
        self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server.bind((host, port))
        self.server.listen(5)
        print(f"Server started on {host}:{port}")
        self.clients = []

    def broadcast(self, message, client_socket):
        for client in self.clients:
            if client != client_socket:
                try:
                    client.send(message)
                except:
                    self.clients.remove(client)

    def handle_client(self, client_socket):
        while True:
            try:
                message = client_socket.recv(1024)
                self.broadcast(message, client_socket)
            except:
                self.clients.remove(client_socket)
                client_socket.close()
                break

    def run(self):
        while True:
            client_socket, client_address = self.server.accept()
            print(f"New connection from {client_address}")
            self.clients.append(client_socket)
            thread = threading.Thread(target=self.handle_client, args=(client_socket,))
            thread.start()


# Client Code
class GameClient:
    def __init__(self, host="127.0.0.1", port=5555):
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client.connect((host, port))
        print(f"Connected to the game server at {host}:{port}")

        receive_thread = threading.Thread(target=self.receive_messages)
        receive_thread.start()

        self.send_messages()

    def receive_messages(self):
        while True:
            try:
                message = self.client.recv(1024).decode("utf-8")
                print(message)
            except:
                print("Disconnected from server.")
                self.client.close()
                break

    def send_messages(self):
        while True:
            message = input()
            self.client.send(message.encode("utf-8"))


# Entry Point
if __name__ == "__main__":
    print("1. Start Server")
    print("2. Start Client")
    choice = input("Choose an option: ")

    if choice == "1":
        server = GameServer()
        server.run()
    elif choice == "2":
        host = input("Enter server IP (default: 127.0.0.1): ") or "127.0.0.1"
        port = int(input("Enter server port (default: 5555): ") or 5555)
        client = GameClient(host, port)
    else:
        print("Invalid option. Exiting.")

14. AI-Powered Chess Engine

This project would require you to implement algorithms like Minimax and Alpha-Beta Pruning to create a competitive AI opponent.

Adding a graphical user interface (GUI) and deploying the game online can make it accessible to a broader audience.

Source code

import chess
import chess.engine
import chess.svg
import random
import time
from flask import Flask, render_template, request

app = Flask(__name__)

# Initialize Stockfish chess engine
ENGINE_PATH = "stockfish"  # Path to the Stockfish binary
engine = chess.engine.SimpleEngine.popen_uci(ENGINE_PATH)

# Game state
game_board = chess.Board()


@app.route("/")
def index():
    return render_template("index.html", board=game_board.fen(), result=game_board.result(claim_draw=True))


@app.route("/make_move", methods=["POST"])
def make_move():
    global game_board

    move = request.form.get("move")
    if move and chess.Move.from_uci(move) in game_board.legal_moves:
        game_board.push(chess.Move.from_uci(move))

        # AI's move
        if not game_board.is_game_over():
            result = engine.play(game_board, chess.engine.Limit(time=1.0))
            game_board.push(result.move)

    return render_template("index.html", board=game_board.fen(), result=game_board.result(claim_draw=True))


@app.route("/reset")
def reset():
    global game_board
    game_board = chess.Board()
    return render_template("index.html", board=game_board.fen(), result=game_board.result(claim_draw=True))


# Flask templates (HTML)
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Chess Engine</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chessboard-js/1.0.0/chessboard.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chessboard-js/1.0.0/chessboard.min.css" />
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; text-align: center; }
        #board { margin: 20px auto; }
        #move-input { margin-top: 10px; }
    </style>
</head>
<body>
    <h1>AI Chess Engine</h1>
    <div id="board"></div>
    <form id="move-form" action="/make_move" method="post">
        <input type="text" id="move-input" name="move" placeholder="Enter your move (e.g., e2e4)" required />
        <button type="submit">Make Move</button>
    </form>
    <button onclick="window.location.href='/reset'">Reset Game</button>
    <script>
        const board = Chessboard('board', {
            draggable: true,
            position: "{{ board }}",
            onDrop: function (source, target) {
                document.getElementById("move-input").value = source + target;
            }
        });
    </script>
</body>
</html>
"""

# Save HTML template
with open("templates/index.html", "w") as file:
    file.write(HTML_TEMPLATE)

if __name__ == "__main__":
    try:
        app.run(debug=True)
    finally:
        engine.quit()

Advanced Python Projects Ideas

You must have a good mix of varied Python projects in your portfolio, ranging from intermediate to advanced and spanning multiple domains. This is not only helpful in strengthening the base of your Python knowledge but also helpful in cracking a top IT job!

Here are some additional advanced Python projects for you to work on!

15. Blockchain-based voting system

This project would involve understanding cryptographic techniques, implementing smart contracts, and designing a user-friendly interface. It’s an excellent way to demonstrate your knowledge of blockchain and Python.

Source code

from hashlib import sha256
from flask import Flask, request, jsonify

app = Flask(__name__)

# Blockchain data structure
class Block:
    def __init__(self, index, previous_hash, timestamp, data, proof):
        self.index = index
        self.previous_hash = previous_hash
        self.timestamp = timestamp
        self.data = data
        self.proof = proof
        self.hash = self.calculate_hash()

    def calculate_hash(self):
        return sha256(f"{self.index}{self.previous_hash}{self.timestamp}{self.data}{self.proof}".encode()).hexdigest()


class Blockchain:
    def __init__(self):
        self.chain = []
        self.current_votes = []
        self.create_genesis_block()

    def create_genesis_block(self):
        genesis_block = Block(0, "0", "2024-01-01T00:00:00", "Genesis Block", 0)
        self.chain.append(genesis_block)

    def get_last_block(self):
        return self.chain[-1]

    def add_block(self, proof, data):
        last_block = self.get_last_block()
        new_block = Block(len(self.chain), last_block.hash, "2024-01-01T00:00:00", data, proof)
        self.chain.append(new_block)

    def proof_of_work(self, last_proof):
        proof = 0
        while not self.valid_proof(last_proof, proof):
            proof += 1
        return proof

    @staticmethod
    def valid_proof(last_proof, proof):
        guess = f"{last_proof}{proof}".encode()
        guess_hash = sha256(guess).hexdigest()
        return guess_hash[:4] == "0000"

    def is_valid_chain(self):
        for i in range(1, len(self.chain)):
            current = self.chain[i]
            previous = self.chain[i - 1]
            if current.hash != current.calculate_hash():
                return False
            if current.previous_hash != previous.hash:
                return False
        return True


# Initialize blockchain
blockchain = Blockchain()

@app.route('/vote', methods=['POST'])
def vote():
    voter_id = request.json['voter_id']
    candidate = request.json['candidate']

    vote_data = {
        'voter_id': voter_id,
        'candidate': candidate
    }
    blockchain.current_votes.append(vote_data)

    return jsonify({"message": "Vote cast successfully!", "current_votes": blockchain.current_votes}), 200


@app.route('/mine', methods=['POST'])
def mine_block():
    last_block = blockchain.get_last_block()
    last_proof = last_block.proof
    proof = blockchain.proof_of_work(last_proof)

    # Include all current votes in the new block
    blockchain.add_block(proof, blockchain.current_votes)
    blockchain.current_votes = []

    return jsonify({"message": "New block mined!", "block": blockchain.chain[-1].__dict__}), 201


@app.route('/chain', methods=['GET'])
def get_chain():
    chain_data = [block.__dict__ for block in blockchain.chain]
    return jsonify({"chain": chain_data, "length": len(chain_data)}), 200


@app.route('/validate', methods=['GET'])
def validate_chain():
    is_valid = blockchain.is_valid_chain()
    return jsonify({"is_valid_chain": is_valid}), 200


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

16. Real-Time language translation tool

This tool can translate spoken or written text from one language to another using advanced NLP techniques and machine learning models.

By integrating this project with APIs for speech recognition and text-to-speech conversion, you can make it highly interactive and practical.

Source code

import speech_recognition as sr
from googletrans import Translator
import pyttsx3

# Initialize speech recognizer
recognizer = sr.Recognizer()

# Initialize Google Translator
translator = Translator()

# Initialize Text-to-Speech engine
engine = pyttsx3.init()

# Function to convert speech to text
def recognize_speech():
    with sr.Microphone() as source:
        print("Listening for your input...")
        try:
            audio = recognizer.listen(source, timeout=10)
            text = recognizer.recognize_google(audio)
            print(f"Recognized speech: {text}")
            return text
        except sr.UnknownValueError:
            print("Sorry, I couldn't understand your speech.")
            return None
        except sr.RequestError:
            print("Could not request results; please check your internet connection.")
            return None

# Function to translate text
def translate_text(input_text, target_language):
    try:
        translated = translator.translate(input_text, dest=target_language)
        print(f"Translated text: {translated.text}")
        return translated.text
    except Exception as e:
        print(f"Error during translation: {e}")
        return None

# Function to convert text to speech
def speak_text(output_text):
    try:
        engine.say(output_text)
        engine.runAndWait()
    except Exception as e:
        print(f"Error during speech synthesis: {e}")

# Supported languages
languages = {
    "spanish": "es",
    "french": "fr",
    "german": "de",
    "hindi": "hi",
    "chinese": "zh-cn",
    "japanese": "ja",
    "korean": "ko"
}

def main():
    print("Welcome to the Real-Time Language Translation Tool!")
    print("Supported languages: Spanish, French, German, Hindi, Chinese, Japanese, Korean")
    target_language_name = input("Enter the target language: ").lower()

    if target_language_name not in languages:
        print(f"Language '{target_language_name}' is not supported. Exiting.")
        return

    target_language_code = languages[target_language_name]
    print(f"Target language selected: {target_language_name.capitalize()} ({target_language_code})")

    print("Say something in English, and I'll translate it.")
    input_text = recognize_speech()

    if input_text:
        translated_text = translate_text(input_text, target_language_code)
        if translated_text:
            speak_text(translated_text)
            print("Translation process completed!")

if __name__ == "__main__":
    main()

17. Disease Prediction System

This system can predict the likelihood of certain diseases by analysing patient data and symptoms, helping doctors make informed decisions.

This project showcases your technical skills and demonstrates your ability to apply them to real-world problems.

Source code

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import pickle

# Load dataset (Replace with your dataset path)
def load_data(file_path):
    try:
        data = pd.read_csv(file_path)
        return data
    except FileNotFoundError:
        print("Dataset not found. Ensure the file path is correct.")
        return None

# Preprocess dataset
def preprocess_data(data):
    X = data.iloc[:, :-1]  # Features
    y = data.iloc[:, -1]   # Target (Disease labels)
    return X, y

# Train the model
def train_model(X_train, y_train):
    model = RandomForestClassifier(n_estimators=100, random_state=42)
    model.fit(X_train, y_train)
    return model

# Save the model to a file
def save_model(model, file_name):
    with open(file_name, 'wb') as file:
        pickle.dump(model, file)
    print(f"Model saved as {file_name}")

# Load the model from a file
def load_model(file_name):
    with open(file_name, 'rb') as file:
        model = pickle.load(file)
    return model

# Predict diseases
def predict_disease(model, symptoms):
    prediction = model.predict([symptoms])
    return prediction[0]

def main():
    print("Welcome to the Disease Prediction System!")
    print("Ensure you have a properly formatted dataset (CSV).")

    # Load dataset
    dataset_path = input("Enter the path to your dataset (CSV): ")
    data = load_data(dataset_path)
    if data is None:
        return

    # Preprocess data
    X, y = preprocess_data(data)

    # Split dataset into training and testing sets
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

    # Train the model
    print("Training the model...")
    model = train_model(X_train, y_train)

    # Evaluate the model
    y_pred = model.predict(X_test)
    accuracy = accuracy_score(y_test, y_pred)
    print(f"Model Accuracy: {accuracy * 100:.2f}%")

    # Save the model
    save_model(model, "disease_prediction_model.pkl")

    # Load the saved model for prediction
    loaded_model = load_model("disease_prediction_model.pkl")

    # Input symptoms for prediction
    print("Enter symptoms for disease prediction (Ensure they match the dataset format).")
    symptoms = [float(x) for x in input("Enter symptom values separated by commas: ").split(",")]

    # Predict disease
    disease = predict_disease(loaded_model, symptoms)
    print(f"The predicted disease is: {disease}")

if __name__ == "__main__":
    main()

18. Dynamic pricing system for e-commerce platforms

By analyzing factors like demand, competition, and customer behaviour, this system can automatically adjust prices to maximize revenue.

Implementing this project will require a deep understanding of data science, machine learning, and business logic.

Source code

import pandas as pd
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import pickle

# Load dataset (Replace with your dataset path)
def load_data(file_path):
    try:
        data = pd.read_csv(file_path)
        return data
    except FileNotFoundError:
        print("Dataset not found. Ensure the file path is correct.")
        return None

# Preprocess dataset
def preprocess_data(data):
    # Handling missing values (if any)
    data.fillna(data.mean(), inplace=True)
    X = data.drop(columns=['price'])  # Features (drop target column)
    y = data['price']  # Target variable
    return X, y

# Train the pricing model
def train_model(X_train, y_train):
    model = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=5, random_state=42)
    model.fit(X_train, y_train)
    return model

# Save the model
def save_model(model, file_name):
    with open(file_name, 'wb') as file:
        pickle.dump(model, file)
    print(f"Model saved as {file_name}")

# Load the model
def load_model(file_name):
    with open(file_name, 'rb') as file:
        model = pickle.load(file)
    return model

# Predict price
def predict_price(model, features):
    predicted_price = model.predict([features])
    return predicted_price[0]

def main():
    print("Welcome to the Dynamic Pricing System for E-commerce Platforms!")
    print("Ensure you have a properly formatted dataset with a 'price' column as the target.")

    # Load dataset
    dataset_path = input("Enter the path to your dataset (CSV): ")
    data = load_data(dataset_path)
    if data is None:
        return

    # Preprocess data
    X, y = preprocess_data(data)

    # Split the data
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

    # Train the model
    print("Training the pricing model...")
    model = train_model(X_train, y_train)

    # Evaluate the model
    y_pred = model.predict(X_test)
    rmse = np.sqrt(mean_squared_error(y_test, y_pred))
    print(f"Model RMSE (Root Mean Squared Error): {rmse:.2f}")

    # Save the model
    save_model(model, "dynamic_pricing_model.pkl")

    # Load the saved model
    loaded_model = load_model("dynamic_pricing_model.pkl")

    # Predict price based on user input
    print("\nEnter feature values for price prediction (Ensure they match the dataset columns).")
    user_features = [float(x) for x in input("Enter feature values separated by commas: ").split(",")]
    price = predict_price(loaded_model, user_features)
    print(f"The predicted price for the given features is: ${price:.2f}")

if __name__ == "__main__":
    main()

19. Vehicle Tracking & Accident Detection System

This system can track vehicle locations and detect accidents in real time using GPS data, accelerometers, and machine learning algorithms.

Integrating it with a mobile app for notifications and emergency services can make this project highly practical.

Source code

import cv2
import numpy as np
import time
from geopy.geocoders import Nominatim
from twilio.rest import Client

# Twilio Configuration for sending SMS alerts
TWILIO_ACCOUNT_SID = "your_twilio_account_sid"
TWILIO_AUTH_TOKEN = "your_twilio_auth_token"
TWILIO_PHONE_NUMBER = "your_twilio_phone_number"
ALERT_PHONE_NUMBER = "recipient_phone_number"

# Initialize geolocator
geolocator = Nominatim(user_agent="vehicle_tracking_system")

# Function to send SMS alert
def send_sms_alert(location):
    client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
    message = f"Accident Detected! Location: {location}"
    client.messages.create(body=message, from_=TWILIO_PHONE_NUMBER, to=ALERT_PHONE_NUMBER)
    print("SMS alert sent!")

# Function to get the approximate location using latitude and longitude
def get_location(latitude, longitude):
    try:
        location = geolocator.reverse((latitude, longitude))
        return location.address
    except Exception as e:
        print(f"Error fetching location: {e}")
        return "Unknown Location"

# Initialize video capture for vehicle tracking
def vehicle_tracking(video_path):
    cap = cv2.VideoCapture(video_path)

    # Pre-trained model for vehicle detection
    net = cv2.dnn.readNet("yolov4.weights", "yolov4.cfg")
    layer_names = net.getLayerNames()
    output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]

    # Define accident detection threshold
    accident_threshold = 50

    # Loop through video frames
    while True:
        ret, frame = cap.read()
        if not ret:
            break

        height, width, _ = frame.shape

        # Object detection
        blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
        net.setInput(blob)
        outs = net.forward(output_layers)

        class_ids = []
        confidences = []
        boxes = []

        for out in outs:
            for detection in out:
                scores = detection[5:]
                class_id = np.argmax(scores)
                confidence = scores[class_id]
                if confidence > 0.5:  # Threshold for detection
                    center_x = int(detection[0] * width)
                    center_y = int(detection[1] * height)
                    w = int(detection[2] * width)
                    h = int(detection[3] * height)

                    # Rectangle coordinates
                    x = int(center_x - w / 2)
                    y = int(center_y - h / 2)

                    boxes.append([x, y, w, h])
                    confidences.append(float(confidence))
                    class_ids.append(class_id)

        indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
        for i in range(len(boxes)):
            if i in indexes:
                x, y, w, h = boxes[i]
                label = str(class_ids[i])
                confidence = confidences[i]
                color = (0, 255, 0)
                cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)

        # Accident detection logic
        if len(boxes) > accident_threshold:  # Simulate accident detection
            print("Accident detected!")
            latitude, longitude = 28.6139, 77.2090  # Example coordinates
            location = get_location(latitude, longitude)
            send_sms_alert(location)
            break

        # Display video with detected objects
        cv2.imshow("Vehicle Tracking", frame)

        # Exit on pressing 'q'
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()

# Main execution
if __name__ == "__main__":
    video_file = "traffic_video.mp4"  # Replace with your video file path
    vehicle_tracking(video_file)

20. Air Quality Monitoring System

Using IoT sensors to collect pollutant data, this system can analyze and display air quality levels in real time.

Implementing this project showcases your ability to work with hardware and software, making it an impressive addition to your portfolio.

Source code

import time
import requests
from flask import Flask, jsonify, render_template
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import random

# Initialize Flask app
app = Flask(__name__)

# Simulate Air Quality Data (Replace this with actual sensor data in a real-world scenario)
def fetch_air_quality_data():
    # Example simulated data with random values
    air_quality_data = {
        "PM2.5": round(random.uniform(10, 150), 2),  # Particulate matter 2.5
        "PM10": round(random.uniform(20, 300), 2),  # Particulate matter 10
        "CO": round(random.uniform(0.1, 10), 2),    # Carbon Monoxide
        "NO2": round(random.uniform(10, 100), 2),   # Nitrogen Dioxide
        "O3": round(random.uniform(10, 200), 2),    # Ozone
        "Timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
    }
    return air_quality_data

# Real-time air quality visualization using Matplotlib
plt.style.use("seaborn")
data_log = {"time": [], "PM2.5": [], "PM10": [], "CO": [], "NO2": [], "O3": []}

def update_chart(frame):
    air_quality = fetch_air_quality_data()
    data_log["time"].append(air_quality["Timestamp"])
    data_log["PM2.5"].append(air_quality["PM2.5"])
    data_log["PM10"].append(air_quality["PM10"])
    data_log["CO"].append(air_quality["CO"])
    data_log["NO2"].append(air_quality["NO2"])
    data_log["O3"].append(air_quality["O3"])

    plt.cla()
    plt.plot(data_log["time"][-10:], data_log["PM2.5"][-10:], label="PM2.5")
    plt.plot(data_log["time"][-10:], data_log["PM10"][-10:], label="PM10")
    plt.plot(data_log["time"][-10:], data_log["CO"][-10:], label="CO")
    plt.plot(data_log["time"][-10:], data_log["NO2"][-10:], label="NO2")
    plt.plot(data_log["time"][-10:], data_log["O3"][-10:], label="O3")
    plt.xlabel("Time")
    plt.ylabel("Concentration")
    plt.title("Real-Time Air Quality Monitoring")
    plt.legend(loc="upper right")
    plt.xticks(rotation=45)
    plt.tight_layout()

# Start real-time chart
def start_visualization():
    ani = FuncAnimation(plt.gcf(), update_chart, interval=2000)
    plt.show()

# Flask API endpoint for fetching data
@app.route('/api/air_quality', methods=['GET'])
def air_quality_api():
    air_quality = fetch_air_quality_data()
    return jsonify(air_quality)

# Flask Webpage to display air quality stats
@app.route('/')
def dashboard():
    return render_template('dashboard.html')

# Start Flask app and real-time chart
if __name__ == "__main__":
    import threading

    # Flask server in a separate thread
    def start_server():
        app.run(debug=False, use_reloader=False)

    # Dashboard Template (HTML)
    with open("templates/dashboard.html", "w") as f:
        f.write('''
        <!DOCTYPE html>
        <html>
        <head>
            <title>Air Quality Monitoring</title>
            <style>
                body { font-family: Arial, sans-serif; text-align: center; background-color: #f7f9fb; }
                h1 { color: #4CAF50; }
                table { margin: auto; border-collapse: collapse; width: 50%; }
                th, td { border: 1px solid #ddd; padding: 8px; }
                th { background-color: #4CAF50; color: white; }
                tr:nth-child(even) { background-color: #f2f2f2; }
            </style>
        </head>
        <body>
            <h1>Real-Time Air Quality Monitoring</h1>
            <p>Data fetched from sensors</p>
            <div id="data"></div>
            <script>
                function fetchAirQualityData() {
                    fetch('/api/air_quality')
                        .then(response => response.json())
                        .then(data => {
                            let html = '<table><tr><th>Pollutant</th><th>Value</th></tr>';
                            for (const [key, value] of Object.entries(data)) {
                                html += `<tr><td>${key}</td><td>${value}</td></tr>`;
                            }
                            html += '</table>';
                            document.getElementById('data').innerHTML = html;
                        });
                }
                setInterval(fetchAirQualityData, 2000);
                fetchAirQualityData();
            </script>
        </body>
        </html>
        ''')

    # Run Flask and Matplotlib simultaneously
    threading.Thread(target=start_server).start()
    start_visualization()