0% found this document useful (0 votes)
42 views81 pages

Python File 3rd Yr

The document is an apprenticeship report by Yashika Paryani from Sant Hirdaram Girls College, Bhopal, focusing on 'Modern WebTech & GenAI' as part of her Bachelor of Computer Science degree. It details the project development process, including the creation of various applications such as a GenAI-powered educational tool, a chatbot, and an eye detection system, showcasing the integration of modern web technologies and generative AI. The report also includes acknowledgments, system requirements, and an overview of the evolution and applications of modern web technologies and AI.

Uploaded by

Yashika
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views81 pages

Python File 3rd Yr

The document is an apprenticeship report by Yashika Paryani from Sant Hirdaram Girls College, Bhopal, focusing on 'Modern WebTech & GenAI' as part of her Bachelor of Computer Science degree. It details the project development process, including the creation of various applications such as a GenAI-powered educational tool, a chatbot, and an eye detection system, showcasing the integration of modern web technologies and generative AI. The report also includes acknowledgments, system requirements, and an overview of the evolution and applications of modern web technologies and AI.

Uploaded by

Yashika
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SANT HIRDARAM GIRLS COLLEGE, BHOPAL

AN APPRENTICESHIP REPORT
ON
“ Modern WebTech & GenAI ”

Submitted in Partial Fulfillment of Requirements for the Award of Degree of


Bachelor of Computer Science

SUBMITTED TO

BARKATULLAH UNIVERSITY, BHOPAL


SUBMITTED BY :

YASHIKA PARYANI

BCA III YEAR

1
SANT HIRDARAM GIRLS COLLEGE, BHOPAL
CERTIFICATE

This is to certify that the work embodies in this apprenticeship work entitled

“Modern WebTech & GenAI” being submitted by

Yashika Paryani in partial fulfillment of the requirement for the award of

Bachelor of Computer Science to Barkatullah University, Bhopal ( M.P.) during

the academic year 2024-25.

Supervisor :
Prof. Manju Devnani
(Computer Science Dept)

2
CERTIFICATE

3
ACKNOWLEDGEMENT

I want to express my appreciation for the chance to carry outa


an apprenticeship MODERN WEBTECH & GENAI. The
management, including Shri Hero Gyanchandani,
Director, Dr Dalima Parwani, Principal, Mr Bhupendra
Khilrani, Instructor and Guide, and Ms Manju Devnani,
Supervisor, alongside the Department of Computer
Science, provided invaluable support and perspectives for
which I am grateful.

4
SANT HIRDARAM GIRLS COLLEGE, BHOPAL

DECLARATION

I Ms. Yashika Paryani, student of BCA III Year, Sant Hirdaram Girls College,

Bhopal M.P., hereby declare that the work presented in this Apprenticeship Report

entitled “Modern WebTech & GenA” is the outcome of my own work, is bonafide

and correct to the best of my knowledge.

Ms. Yashika Paryani

BCA III Year

5
ABSTRACT

Introduction to the Project Development Process


Our project development journey began with learning essential Modern Web Technologies,
including HTML, CSS, and JavaScript for building interactive frontends, and Python with
Flask for robust backend development. We also explored the integration of Generative AI
APIs, Computer Vision libraries like OpenCV, and practical logic implementation for
administrative tools.
1. Flashcard Learn: Developed a GenAI-powered educational tool that automatically
creates study materials based on user-selected topics. The system was built using Flask
to manage API interactions, providing a dynamic and personalized learning experience.
2. Chatbot: Implemented an intelligent conversational agent using Natural Language
Processing (NLP) and GenAI models. The application features a responsive chat
interface where users can interact with the bot to receive instant, context-aware
responses.
3. Flask IoT Day/Night Detector: Created a dynamic web application that automatically
toggles the visual theme between day and night modes based on detection logic. This
project demonstrated the integration of backend state management with frontend styling
to create adaptive user interfaces.
4. Eye Detection System: Integrated computer vision using OpenCV to detect facial
landmarks and track eye status in real-time. This system processes video input to
identify user presence or gestures, showcasing the synergy between Python processing
and web visualization.
5. Portfolio: Designed a professional, fully responsive personal website to act as a digital
resume. We utilized modern CSS frameworks and design principles to ensure the
interface effectively showcases skills, projects, and contact information across all
devices.
6. Fees Collection & Receipt System: Built a practical administrative tool for managing
payments and generating digital receipts. The system uses Flask to handle form data
processing, calculations, and record generation, simulating a real-world financial
transaction utility.
These projects provided practical experience in Full-Stack Web Development, AI integration,
Computer Vision, and automated system design, enhancing our technical skills and problem-
solving abilities.

6
INDEX

Sr. TABLE OF CONTENT TOPICS PAGE


No. NO.

1. Certificate 2
2. Acknowledgement 4
3. Declaration 5
4. Abstract 6
5. Introduction To Modern Webtech And Gen AI 8
6. Applications of Modern Webtech And GenAI 9
7. System requirements 10
8. Implementations of Project : 11-30
[Link] Learn
9. 2. Chatbot 31-36
10. 3. Flask IoT Day/Night Detector 37-41

11. [Link] detection system 42-48

12. [Link] 49-63


13. 6. Fees collection & Receipt system 64-78

14. Conclusion 79
15. References / Bibliography / Webiography 80

7
MODERN WEBTECH AND GEN AI

The contemporary digital ecosystem is being profoundly reshaped by the powerful confluence of two
technological paradigms: Modern Web Technologies (WebTech) and Generative Artificial Intelligence
(GenAI). While Modern WebTech provides the robust and interactive platforms for digital experiences, GenAI
infuses these platforms with unprecedented intelligence, creativity, and personalization. This convergence is
not merely an incremental update; it represents a fundamental shift in how we design, develop, and interact
with web applications, paving the way for a new era of the internet that is more dynamic, intuitive, and human-
centric.

The Evolution and Core Tenets of Modern WebTech


The web has evolved dramatically from its origins as a repository of static, hyperlinked documents. The
journey to the modern web has been marked by a relentless pursuit of richer, more interactive user experiences,
effectively blurring the line between desktop and web applications. Modern WebTech is the culmination of
this evolution, built upon a set of core principles and a powerful stack of technologies.

Key Principles:
• Component-Based Architecture: Instead of building monolithic pages, modern web development treats
the user interface (UI) as a collection of reusable, self-contained components. Frameworks like React
the flagbearers of this approach, allowing developers to build complex UIs by composing simple,
independent parts.
• Single-Page Applications (SPAs): SPAs provide a seamless and fluid user experience by loading a
single HTML page and dynamically updating its content as the user interacts with the app. This avoids
disruptive page reloads, creating an experience that feels fast and responsive, much like a native mobile
or desktop application.
• API-Centric Design: Modern web applications are typically architected with a decoupled frontend and
backend. The frontend (client-side) communicates with the backend (server-side) through Application
Programming Interfaces (APIs), usually RESTful or GraphQL APIs. The Dawn of Generative AI
Artificial Intelligence has traditionally excelled at analytical tasks—classifying data, recognizing patterns,
and making predictions based on existing information (discriminative AI). Generative AI represents a
paradigm shift. Instead of just interpreting data, it creates new, original content that is contextually
Capabilities:
• The scope of GenAI's creative power is vast and expanding:
• Text Generation: Writing emails, articles, marketing copy, poetry, and summarizing complex
documents.
• Code Generation: Assisting developers by writing functions, generating boilerplate code, and
debugging.
• Image and Art Generation: Creating photorealistic images, illustrations, and artistic pieces from
text descriptions.
• Audio and Music Generation: Composing musical scores, generating sound effects, and creating
synthetic voices.

8
APPLICATION OF MODERN WEBTECH & AI

The integration of Generative AI into modern web applications has unlocked a wide range of
innovative use cases across various industries. These applications go beyond simple
automation, offering dynamic and intelligent user experiences.

1. Hyper-Personalization at Scale:
While personalization is not a new concept, GenAI takes it to an unprecedented level. E-commerce
and streaming platforms can now generate dynamic user interfaces and product descriptions in real-
time based on user behavior.

2. Next-Generation Conversational AI:


The era of rigid, script-based chatbots is over. Modern websites are embedding sophisticated GenAI-
powered virtual assistants that can understand context, handle complex multi-turn conversations, and
perform actions by integrating with backend systems.

3. Content Creation and Creative Partnership:


GenAI is acting as a powerful co-pilot for content creators and marketers. Blogging platforms can
integrate AI to help draft articles, generate headlines, and suggest structural improvements.

4. Accelerated Software Development:


The software development lifecycle is being supercharged by AI-powered tools. Services like GitHub
Copilot, integrated directly into code editors, can suggest entire blocks of code, write documentation,
generate unit tests, and even explain complex algorithms in plain language.

5. Personalized and Adaptive Education:


GenAI is transforming the learning experience from a one-size-fits-all model to a personalized journey.
Educational platforms can create customized study materials, generate practice questions tailored to a
student's weak points, and offer interactive AI tutors that can explain complex topics in multiple ways.

6. Enhanced Search and Data Discovery:


Web search is evolving from keyword matching to a conversational discovery process. GenAI-
powered search engines can understand complex, natural language queries, synthesize information
from multiple sources, and provide direct, summarized answers instead of just a list of links.

7. Dynamic Entertainment and Gaming:


In the world of entertainment, GenAI can generate dynamic and ever-changing content. Video games
can feature non-player characters (NPCs) with unique, unscripted dialogue in every playthrough.

9
SYSTEM REQUIREMENTS

Overall System Requirements for Data Science & Machine Learning


Projects
Hardware Requirements
● Processor: Intel i5 or equivalent (minimum)
● RAM: 8 GB (16 GB recommended for optimal performance)
● Disk Space: 10 GB or more (depending on data size and model complexity)
● GPU: Optional, but recommended for large-scale machine learning models (e.g., for deep learning or
large datasets)

Software Requirements

• Operating System: Windows 10/11, macOS, or any major Linux distribution (like Ubuntu) are all
suitable.
• Code Editor: A modern source-code editor such as Visual Studio Code is highly recommended due
to its vast ecosystem of extensions for web development, Python, and AI.
• Web Browser: An up-to-date browser like Google Chrome or Microsoft Edge is essential for testing
and debugging the frontend.
• Core Languages & Runtimes:
➢ Python (3.8+): The primary language for the backend server.
➢ [Link]: Useful for frontend build tools and package management, though not strictly required
for these specific projects.
• Version Control: Git should be used for source code management, along with a GitHub account for
repository hosting and collaboration.

Key Frameworks, Libraries, and APIs


• Backend Framework:
o Flask: A lightweight Python web framework used to create the server, define API endpoints, and
handle logic.
o Flask-SocketIO: A Flask extension for enabling real-time, bidirectional communication between
the server and the client, crucial for the Eye Gesture Detection project.
• Generative AI Integration:
o Google AI Python SDK: The official library for interacting with the Gemini API.
▪ Installation: pip install google-generativeai
• Computer Vision:
o OpenCV: Used to capture video from the webcam.
▪ Installation: pip install opencv-python
o Dlib: A powerful toolkit for machine learning, used here specifically for its highly accurate facial
landmark detection.
▪ Installation: pip install dlib
• Frontend Technologies:
o HTML5, CSS3, JavaScript: The fundamental building blocks of the web pages and user interfaces
for all projects.
This integrated system provides all the necessary tools for data analysis, machine learning.
10
IMPLEMENTATION
1. Flashcards Learn App
Project Overview: The Flashcards Learn App is a web-based educational tool designed to help users study any
topic by automatically generating flashcards. Using Generative AI, the application takes a user-specified topic
and creates a set of relevant questions and answers, providing an efficient and interactive learning experience.

❖ Project Structure:
LEARNING_PROJECT/

├── backend/
│ ├── [Link] # Main Flask API
│ ├── [Link] # Database models
│ ├── auth_utils.py # JWT authentication
│ ├── email_service.py # Email/OTP service
│ ├── [Link] # Dependencies
│ ├── [Link] # Deployment config
│ └── .env # Environment variables

└── frontend/
├── public/
│ └── [Link]
├── src/
│ ├── [Link] # Main React app
│ ├── [Link] # All styles
│ ├── [Link] # Entry point
│ ├── [Link] # Auth components
│ ├── [Link] # Auth utilities
│ ├── [Link] # Global styles
│ └── assets/
│ └── [Link]
├── [Link]
├── [Link]

11
❖ Coding of [Link]
from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime, ForeignKey, func
from [Link] import declarative_base
from [Link] import sessionmaker, relationship
from [Link] import generate_password_hash, check_password_hash

DATABASE_URL = "sqlite:///[Link]"
engine = create_engine(DATABASE_URL, echo=False)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, autoincrement=True)
username = Column(String(50), nullable=False, unique=True)
email = Column(String(100), nullable=False, unique=True)
password_hash = Column(Text, nullable=False)
role = Column(String(20), nullable=False)
email_verified = Column(String(5), nullable=False, default='false')
otp_code = Column(String(6), nullable=True)
otp_expires_at = Column(DateTime, nullable=True)
otp_attempts = Column(Integer, nullable=False, default=0)

def set_password(self, password):


self.password_hash = generate_password_hash(password)

def check_password(self, password):


return check_password_hash(self.password_hash, password)

def to_dict(self):
return {
"id": [Link],
"username": [Link],
"email": [Link],
"role": [Link],
"email_verified": self.email_verified == 'true'
}

class Deck(Base):
__tablename__ = "decks"
id = Column(Integer, primary_key=True, autoincrement=True)

12
name = Column(Text, nullable=False)
description = Column(Text)
created_by = Column(String(50), nullable=True)
flashcards = relationship("Flashcard", back_populates="deck", cascade="all, delete-orphan")

class Flashcard(Base):
__tablename__ = "flashcards"
id = Column(Integer, primary_key=True, autoincrement=True)
front_text = Column(Text, nullable=False)
back_text = Column(Text, nullable=False)
deck_id = Column(Integer, ForeignKey("[Link]"), nullable=False)
deck = relationship("Deck", back_populates="flashcards")

def create_tables():
[Link].create_all(bind=engine)

def get_db():
db = SessionLocal()
try:
yield db
finally:
[Link]()

❖ Coding of [Link]

from flask import Flask, request, jsonify


from flask_cors import CORS
from models import create_tables, get_db, User, Deck, Flashcard
from datetime import datetime, timedelta
import os, secrets
app = Flask(__name__)
CORS(app)

create_tables()
# Simple in-memory OTP generator (for demo)
def generate_otp():
return str([Link](900000)+100000)
@[Link]('/api/signup', methods=['POST'])
def signup():
data = request.get_json() or {}
required = ['username','email','password','role']
for r in required:
if r not in data or not data[r]:
return jsonify({"error": f"{r} required"}), 400
13
db = next(get_db())
if [Link](User).filter([Link]==data['username']).first():
return jsonify({"error":"username exists"}), 400
user = User(username=data['username'], email=data['email'], role=data['role'])
user.set_password(data['password'])
user.otp_code = generate_otp()
user.otp_expires_at = [Link]() + timedelta(minutes=10)
[Link](user); [Link](); [Link](user)
# For demo, return OTP in response (replace with email sending)
return jsonify({"message":"registered","otp":user.otp_code, "user": user.to_dict()}), 201
@[Link]('/api/verify-email', methods=['POST'])
def verify_email():
data = request.get_json() or {}
username = [Link]('username'); otp = [Link]('otp_code')
db = next(get_db())
user = [Link](User).filter([Link]==username).first()
if not user: return jsonify({"error":"not found"}), 404
if user.otp_code == otp and user.otp_expires_at and [Link]() <= user.otp_expires_at:
user.email_verified = 'true'; user.otp_code=None; [Link]()
return jsonify({"message":"verified","user":user.to_dict()})
return jsonify({"error":"invalid or expired otp"}), 400
@[Link]('/api/login', methods=['POST'])
def login():
data = request.get_json() or {}
db = next(get_db())
user = [Link](User).filter([Link]==[Link]('username')).first()
if not user or not user.check_password([Link]('password','')):
return jsonify({"error":"invalid credentials"}), 401
return jsonify({"message":"ok","user":user.to_dict()})

# Deck endpoints (minimal)


@[Link]('/api/decks', methods=['GET','POST'])
def decks():
db = next(get_db())
if [Link]=='GET':
decks = [Link](Deck).all()
return jsonify([{"id":[Link],"name":[Link],"created_by":d.created_by} for d in decks])
data = request.get_json() or {}
if 'name' not in data: return jsonify({"error":"name required"}), 400
deck = Deck(name=data['name'], description=[Link]('description',''), created_by=[Link]('created_by'))
[Link](deck); [Link](); [Link](deck)
return jsonify({"id":[Link],"name":[Link]}), 201

14
if __name__ == "__main__":
[Link](port=5000, debug=True)

❖ Coding of [Link]
import React, { useState, useEffect } from 'react'
import { authUtils } from './authUtils'
const API_BASE = [Link] ? '[Link] : '[Link]
export default function App(){
const [user, setUser] = useState(null)
useEffect(()=> {
const token = [Link]()
if(token) { /* call verify-token if implemented */ }
},[])
if(!user){
return <AuthPanel onLogin={(u)=> setUser(u)} />
}
if([Link]==='admin') return <AdminPanel user={user} onLogout={()=>{[Link](); setUser(null)}}
/>
return <StudentPanel user={user} onLogout={()=> {[Link](); setUser(null)}} />
}
function AuthPanel({onLogin}){
const [form,setForm] = useState({username:'',password:''})
const submit = async (e) => {
[Link]()
const res = await fetch(`${API_BASE}/login`, {method:'POST', headers:{'Content-Type':'application/json'},
body:[Link](form)})
if([Link]){ const json = await [Link](); onLogin([Link]) } else { alert('Login failed') }
}
return (
<form onSubmit={submit}>
<input value={[Link]} onChange={e=>setForm({...form,username:[Link]})}
placeholder="username" />
<input type="password" value={[Link]} onChange={e=>setForm({...form,password:[Link]})}
placeholder="password" />
<button>Login</button>
</form>
)
}

15
❖ Coding of auth_utils.jsx
"""
JWT Token utility for user authentication and session management
"""
import jwt
import os
from datetime import datetime, timedelta
from functools import wraps
from flask import request, jsonify
from dotenv import load_dotenv

load_dotenv()

# Get secret key from environment


SECRET_KEY = [Link]('FLASK_SECRET_KEY', 'your-super-secret-key-change-this-in-production')

def generate_token(user_data):
"""
Generate JWT token for user
"""
payload = {
'user_id': user_data['id'],
'username': user_data['username'],
'email': user_data['email'],
'role': user_data['role'],
'exp': [Link]() + timedelta(days=7), # Token expires in 7 days
'iat': [Link](),
'email_verified': user_data.get('email_verified', 'false')
}

token = [Link](payload, SECRET_KEY, algorithm='HS256')


return token

def verify_token(token):
"""
Verify JWT token and return user data
"""
try:
payload = [Link](token, SECRET_KEY, algorithms=['HS256'])
return {
'success': True,
'data': payload
}
except [Link]:
return {
'success': False,
'error': 'Token has expired'
}
except [Link]:
return {
'success': False,
'error': 'Invalid token'
16
}

def token_required(f):
"""
Decorator to require valid JWT token for protected routes
"""
@wraps(f)
def decorated_function(*args, **kwargs):
token = [Link]('Authorization')

if not token:
return jsonify({'error': 'Token is missing'}), 401

# Remove 'Bearer ' prefix if present


if [Link]('Bearer '):
token = token[7:]

result = verify_token(token)

if not result['success']:
return jsonify({'error': result['error']}), 401

# Add user data to request context


request.current_user = result['data']
return f(*args, **kwargs)

return decorated_function

def get_current_user():
"""
Get current user from request context
"""
return getattr(request, 'current_user', None)

def create_auth_response(user_data, message="Success"):


"""
Create standardized authentication response with token
"""
token = generate_token(user_data)

return {
'message': message,
'token': token,
'user': user_data,
'expires_in': 7 * 24 * 60 * 60 # 7 days in seconds
}
❖ Coding of [Link]
// Authentication utility functions for token management

// Environment-based API configuration


const API_BASE_URL = [Link] === 'localhost'
? '[Link] // Development
: '[Link] // Production
17
const AUTH_TOKEN_KEY = 'flashlearn_auth_token';
const USER_DATA_KEY = 'flashlearn_user_data';

export const authUtils = {


// Save authentication data
saveAuth: (token, userData) => {
[Link](AUTH_TOKEN_KEY, token);
[Link](USER_DATA_KEY, [Link](userData));
},

// Get stored token


getToken: () => {
return [Link](AUTH_TOKEN_KEY);
},

// Get stored user data


getUserData: () => {
const userData = [Link](USER_DATA_KEY);
return userData ? [Link](userData) : null;
},

// Check if user is authenticated


isAuthenticated: () => {
const token = [Link]();
const userData = [Link]();
return !!(token && userData);
},

// Clear authentication data (logout)


clearAuth: () => {
[Link](AUTH_TOKEN_KEY);
[Link](USER_DATA_KEY);
},

// Verify token with backend


verifyToken: async (token) => {
try {
const response = await fetch(`${API_BASE_URL}/verify-token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: [Link]({ token }),
});

const data = await [Link]();


return [Link] ? [Link] : null;
} catch (error) {
[Link]('Token verification failed:', error);
return null;
}
},

18
// Auto-login check on app startup
checkAutoLogin: async () => {
const token = [Link]();
if (!token) return null;

const userData = await [Link](token);


if (userData) {
[Link](token, userData);
return userData;
} else {
[Link]();
return null;
}
},

// Get authorization header for API requests


getAuthHeader: () => {
const token = [Link]();
return token ? { 'Authorization': `Bearer ${token}` } : {};
}
};
❖ Coding of [Link]
/* Global Styles and Variables */
:root {
--primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
--admin-gradient: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
--teacher-gradient: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
--student-gradient: linear-gradient(135deg, #45b7d1 0%, #96c93d 100%);
--success-gradient: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
--warning-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
--danger-gradient: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
--info-gradient: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
--dark-gradient: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
--background-gradient: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
--card-shadow: 0 15px 35px rgba(0,0,0,0.08);
--card-hover-shadow: 0 25px 50px rgba(0,0,0,0.15);
--border-radius: 20px;
--transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
--blur-amount: 20px;
}

*{
box-sizing: border-box;
}

body {
font-family: 'Inter', 'SF Pro Display', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: var(--background-gradient);
margin: 0;
padding: 0;
min-height: 100vh;
line-height: 1.6;
color: #2c3e50;
overflow-x: hidden;

19
}

#root {
margin: 0;
padding: 0;
min-height: 100vh;
}

/* Gradient Text Effects */


.gradient-text {
background: var(--primary-gradient);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
font-weight: 700;
display: inline-block;
}

.admin-gradient-text {
background: var(--admin-gradient);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
font-weight: 700;
}

.teacher-gradient-text {
background: var(--teacher-gradient);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
font-weight: 700;
}

.student-gradient-text {
background: var(--student-gradient);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
font-weight: 700;
}

/* Enhanced Cards with Glassmorphism */


.modern-card {
background: rgba(255, 255, 255, 0.25);
backdrop-filter: blur(var(--blur-amount));
border: 1px solid rgba(255, 255, 255, 0.18);
border-radius: var(--border-radius);
box-shadow: var(--card-shadow);
transition: var(--transition);
overflow: hidden;
position: relative;
padding: 1.5rem;
}

.modern-card::before {
content: '';
position: absolute;

20
top: 0;
left: 0;
right: 0;
height: 4px;
background: var(--primary-gradient);
opacity: 0;
transition: var(--transition);
}

.modern-card:hover::before {
opacity: 1;
}

.modern-card:hover {
transform: translateY(-10px);
box-shadow: var(--card-hover-shadow);
border-color: rgba(255, 255, 255, 0.3);
}

/* Dashboard Statistics Cards */


.dashboard-stats-card {
background: rgba(255, 255, 255, 0.9);
backdrop-filter: blur(30px);
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: var(--border-radius);
padding: 1.5rem 1rem;
text-align: center;
position: relative;
overflow: hidden;
transition: var(--transition);
box-shadow: var(--card-shadow);
}

.dashboard-stats-card::after {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
transition: left 0.6s;
}

.dashboard-stats-card:hover::after {
left: 100%;
}

.dashboard-stats-card:hover {
transform: translateY(-8px);
box-shadow: var(--card-hover-shadow);
}

.dashboard-stats-card .stat-number {
font-size: 3.5rem;
font-weight: 800;
margin-bottom: 0.5rem;
background: var(--primary-gradient);

21
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}

.dashboard-stats-card .stat-label {
font-size: 1rem;
font-weight: 600;
color: #6c757d;
text-transform: uppercase;
letter-spacing: 1px;
}

/* Enhanced Buttons */
.btn-gradient {
background: var(--primary-gradient);
border: none;
color: white;
border-radius: 50px;
padding: 14px 32px;
font-weight: 600;
font-size: 1rem;
transition: var(--transition);
position: relative;
overflow: hidden;
text-transform: uppercase;
letter-spacing: 1px;
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.btn-gradient::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
transition: left 0.6s;
}

.btn-gradient:hover::before {
left: 100%;
}

.btn-gradient:hover {
transform: translateY(-3px);
box-shadow: 0 15px 35px rgba(102, 126, 234, 0.4);
color: white;
}

.btn-gradient:active {
transform: translateY(-1px);
}

/* Role-specific button styles */


.btn-admin {
background: var(--admin-gradient);

22
box-shadow: 0 8px 25px rgba(255, 107, 107, 0.3);
}

.btn-admin:hover {
box-shadow: 0 15px 35px rgba(255, 107, 107, 0.4);
color: white;
}

.btn-teacher {
background: var(--teacher-gradient);
box-shadow: 0 8px 25px rgba(78, 205, 196, 0.3);
}

.btn-teacher:hover {
box-shadow: 0 15px 35px rgba(78, 205, 196, 0.4);
color: white;
}

.btn-student {
background: var(--student-gradient);
box-shadow: 0 8px 25px rgba(69, 183, 209, 0.3);
}

.btn-student:hover {
box-shadow: 0 15px 35px rgba(69, 183, 209, 0.4);
color: white;
}

/* Enhanced Navbar */
.navbar-modern {
background: rgba(255, 255, 255, 0.95) !important;
backdrop-filter: blur(var(--blur-amount));
border-bottom: 1px solid rgba(255, 255, 255, 0.2);
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
padding: 1.2rem 0;
position: relative;
}

.navbar-brand-modern {
font-size: 1.8rem;
font-weight: 800;
text-decoration: none;
position: relative;
transition: var(--transition);
}

.navbar-brand-modern:hover {
transform: scale(1.05);
}

/* Animations */
.animate-fadeIn {
animation: fadeIn 0.8s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

23
❖ Coding of email_service.py
import os
import random
import string
import smtplib
from [Link] import MIMEText
from [Link] import MIMEMultipart
from datetime import datetime, timedelta
from dotenv import load_dotenv

# Load environment variables


load_dotenv()

class GmailService:
def __init__(self):
self.sender_email = [Link]('SENDER_EMAIL')
self.app_name = [Link]('APP_NAME', 'FlashLearn')

# For simplicity, we'll use SMTP instead of OAuth2 for now


# You can upgrade to OAuth2 later if needed
self.smtp_server = "[Link]"
self.smtp_port = 587

# Note: You'll need to set up an App Password in Gmail


# This is a simpler approach than full OAuth2
self.app_password = [Link]('GMAIL_APP_PASSWORD') # Add this to .env

def generate_otp(self):
"""Generate a 6-digit OTP"""
return ''.join([Link]([Link], k=6))

def send_otp_email(self, recipient_email, otp_code, username):


"""Send OTP verification email"""
try:
# Validate configuration
if not self.sender_email or not self.app_password:
return False, "Email configuration is incomplete. Check SENDER_EMAIL and
GMAIL_APP_PASSWORD in .env file."

# Create message
msg = MIMEMultipart()
msg['From'] = self.sender_email
msg['To'] = recipient_email
msg['Subject'] = f"{self.app_name} - Email Verification"

# Email body
html_body = f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body {{ font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f5f5f5; }}
24
.container {{ max-width: 600px; margin: 0 auto; background-color: white; padding: 30px;
border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }}
.header {{ text-align: center; margin-bottom: 30px; }}
.logo {{ color: #667eea; font-size: 24px; font-weight: bold; }}
.otp-code {{ background-color: #f8f9fa; border: 2px dashed #667eea; padding: 20px; text-align:
center; font-size: 32px; font-weight: bold; color: #667eea; letter-spacing: 8px; margin: 20px 0; border-
radius: 8px; }}
.footer {{ margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; font-size: 12px;
color: #666; text-align: center; }}
</style>
</head>
<body>
<div class="container">
<div class="header">
<div class="logo"> {self.app_name}</div>
<h2>Email Verification Required</h2>
</div>

<p>Hello <strong>{username}</strong>,</p>

<p>Welcome to {self.app_name}! To complete your registration, please verify your email


address using the OTP code below:</p>

<div class="otp-code">{otp_code}</div>

<p><strong>Important:</strong></p>
<ul>
<li>This OTP will expire in <strong>10 minutes</strong></li>
<li>You have <strong>4 attempts</strong> to enter the correct OTP</li>
<li>Do not share this code with anyone</li>
</ul>

<p>If you didn't create an account with {self.app_name}, please ignore this email.</p>

<div class="footer">
<p>This is an automated message from {self.app_name}. Please do not reply to this
email.</p>
<p>© 2025 {self.app_name}. All rights reserved.</p>
</div>
</div>
</body>
</html>
"""

[Link](MIMEText(html_body, 'html'))

# Send email using SMTP (simpler than OAuth2)


with [Link](self.smtp_server, self.smtp_port) as server:
[Link]()
[Link](self.sender_email, self.app_password)
server.send_message(msg)

return True, "OTP email sent successfully"


25
except [Link] as e:
error_msg = str(e)
if "Application-specific password required" in error_msg:
return False, "Gmail App Password required. Please set up 2FA and generate an App Password in
your Google Account Security settings."
else:
return False, f"Gmail authentication failed: {error_msg}"
except [Link] as e:
return False, f"Email sending failed: {str(e)}"
except Exception as e:
return False, f"Failed to send OTP email: {str(e)}"

def send_test_result_email(self, recipient_email, username, test_data):


"""Send test result email to student"""
try:
# Calculate percentage
percentage = round((test_data['score'] / test_data['totalQuestions']) * 100)

# Determine performance level


if percentage >= 80:
performance_level = "Excellent! "
performance_color = "#28a745"
elif percentage >= 70:
performance_level = "Good Job! "
performance_color = "#17a2b8"
elif percentage >= 60:
performance_level = "Keep Practicing! "
performance_color = "#ffc107"
else:
performance_level = "Need More Practice "
performance_color = "#dc3545"

# Create message
msg = MIMEMultipart()
msg['From'] = self.sender_email
msg['To'] = recipient_email
msg['Subject'] = f"{self.app_name} - Test Result: {test_data['deckName']}"

# Email body
html_body = f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body {{ font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f5f5f5; }}
.container {{ max-width: 600px; margin: 0 auto; background-color: white; padding: 30px;
border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }}
.header {{ text-align: center; margin-bottom: 30px; }}
.logo {{ color: #667eea; font-size: 24px; font-weight: bold; }}
.score-card {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;
padding: 20px; border-radius: 10px; text-align: center; margin: 20px 0; }}
26
.score-number {{ font-size: 48px; font-weight: bold; }}
.performance {{ color: {performance_color}; font-size: 18px; font-weight: bold; margin: 10px
0; }}
.results-table {{ width: 100%; border-collapse: collapse; margin: 20px 0; }}
.results-table th, .results-table td {{ padding: 10px; text-align: left; border-bottom: 1px solid
#eee; }}
.results-table th {{ background-color: #f8f9fa; font-weight: bold; }}
.correct {{ color: #28a745; font-weight: bold; }}
.incorrect {{ color: #dc3545; font-weight: bold; }}
.footer {{ margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; font-size: 12px;
color: #666; text-align: center; }}
</style>
</head>
<body>
<div class="container">
<div class="header">
<div class="logo"> {self.app_name}</div>
<h2>Test Results</h2>
</div>

<p>Hello <strong>{username}</strong>,</p>

<p>You have completed the test for <strong>"{test_data['deckName']}"</strong>. Here are


your results:</p>

<div class="score-card">
<div class="score-number">{percentage}%</div>
<p>You scored {test_data['score']} out of {test_data['totalQuestions']} questions
correctly</p>
</div>

<div class="performance">{performance_level}</div>

<p><strong>Test Details:</strong></p>
<ul>
<li>Deck: {test_data['deckName']}</li>
<li>Questions: {test_data['totalQuestions']}</li>
<li>Correct Answers: {test_data['score']}</li>
<li>Incorrect Answers: {test_data['totalQuestions'] - test_data['score']}</li>
<li>Completion Date: {[Link](test_data['completedAt'].replace('Z',
'')).strftime('%B %d, %Y at %I:%M %p')}</li>
</ul>

<p>Keep up the great work and continue learning! </p>

<div class="footer">
<p>This is an automated message from {self.app_name}. Please do not reply to this
email.</p>
<p>© 2025 {self.app_name}. All rights reserved.</p>
</div>
</div>
</body>
</html>
27
"""

[Link](MIMEText(html_body, 'html'))

# Send email
with [Link](self.smtp_server, self.smtp_port) as server:
[Link]()
[Link](self.sender_email, self.app_password)
server.send_message(msg)

return True, "Test result email sent successfully"

except [Link] as e:
error_msg = str(e)
if "Application-specific password required" in error_msg:
return False, "Gmail App Password required. Please set up 2FA and generate an App Password in
your Google Account Security settings."
else:
return False, f"Gmail authentication failed: {error_msg}"
except [Link] as e:
return False, f"Email sending failed: {str(e)}"
except Exception as e:
return False, f"Failed to send test result email: {str(e)}"

# Create singleton instance


gmail_service = GmailService()

28
❖ OUTPUT

29
30
2. CHATBOT
This project focuses on developing an intelligent chatbot capable of understanding user queries and providing
relevant, context-aware responses. The chatbot leverages Natural Language Processing (NLP) techniques and
Machine Learning models to interpret user intent accurately and respond efficiently. It is integrated into a
Flask web application, where users can interact through a simple and userfriendly interface. The backend
model processes text input, predicts intent, and generates meaningful replies based on pre-trained data. The
system ensures quick and accurate conversations, making it adaptable for various use cases such as customer
support, information retrieval, and automation of common queries.
❖ PROJECT STRUCTURE
Chatbot/
├── [Link]
├── [Link]
├── scripts/
│ ├── [Link]
│ └── [Link]
└── styles/
└── [Link]

❖ Coding of [Link]
const chatBox = [Link]('chatBox'); const chatForm =
[Link]('chatForm'); const userInput = [Link]('userInput');
const jokes = [
"Why don't scientists trust atoms? Because they make up everything! ",
"Why did the programmer quit his job? Because he didn't get arrays! ",
"What do you call fake spaghetti? An impasta! ",
"Why did the bicycle fall over? It was two-tired! ",
];
const facts = [
"Honey never spoils! ",
"Bananas are berries, but strawberries aren't! ",
"Octopuses have three hearts! ",
"Sharks existed before trees! ",
];
const botResponses = new Map([
[['hi', 'hello', 'hey'], "Hello! How can I help you today?"],
[['good morning'], "Good morning! "],
[['good night'], "Good night! Sweet dreams!"],
[['your name'], "I'm SmartBot , your friendly AI assistant!"],
[['how are you'], "I'm great! How about you?"],
[['help'], " I can tell jokes, facts, do math & chat with you!"],
[['joke'], () => jokes[[Link]([Link]() * [Link])]],
[['fact'], () => facts[[Link]([Link]() * [Link])]],
[['time'], () => ` ${new Date().toLocaleTimeString()}`],
[['date'], () => ` ${new Date().toLocaleDateString()}`],
[['bye', 'goodbye'], "Goodbye! Have a nice day!"],
31
]);
function handleMath(input) {
try {
const expr = [Link](/what is|calculate|solve/gi, '').trim(); if (/^[\d\s+\-*/().%]+$/.test(expr)) return
` ${expr} = ${eval(expr)}`;
} catch {}
return "Please enter a valid math expression (e.g., 2+2)";
}
function getBotResponse(msg) { msg = [Link]().trim(); if (/what is|calculate|solve|\d+[\+\-
\*\/]\d+/.test(msg)) return handleMath(msg); for (const [keys, res] of botResponses) if ([Link](k =>
[Link](k))) return typeof res === 'function' ? res() : res; return " I’m not sure about that. Type
'help' for options!";
}
function appendMessage(text, sender) { const div = [Link]('div'); [Link] =
sender; [Link] = text; [Link](div);
[Link] = [Link];
}
let chatHistory = [Link]([Link]('chatHistory') || '[]'); function saveChat() {
[Link]('chatHistory', [Link](chatHistory)); }
[Link] = () => { if (![Link]) { const greet = "Hi! I'm SmartBot Type 'help' to see
what I can do."; appendMessage(greet, 'bot'); [Link]({ text: greet, sender: 'bot' });
saveChat();
} else [Link](m => appendMessage([Link], [Link])); };
[Link]('submit', e => { [Link](); const userMsg = [Link](); if
(!userMsg) return; appendMessage(userMsg, 'user'); [Link]({ text: userMsg, sender: 'user' });
saveChat(); [Link] = ''; setTimeout(() => { const botMsg = getBotResponse(userMsg);
appendMessage(botMsg, 'bot'); [Link]({ text: botMsg, sender: 'bot' }); saveChat();
}, 500);
});
[Link]('clearChat').onclick = () => {
if (confirm('Clear chat history?')) { chatHistory = []; saveChat(); [Link] = '';
appendMessage("Hi! I'm SmartBot Type 'help' to see what I can do.", 'bot');
}
};

❖ Coding of [Link]
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: linear-gradient(135deg,
#e3f2fd 0%, #f3e5f5 100%); min-height: 100vh;
} .chat-box { height: 400px; overflow-y: auto; background: linear-gradient(135deg, #f5f7fa, #c3cfe2);
border-radius: 12px; padding: 15px; box-shadow: inset 0 2px 8px rgba(0,0,0,0.1);
}
.chat-box::-webkit-scrollbar { width: 8px; }
.chat-box::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 10px; }
.chat-box::-webkit-scrollbar-thumb { background: #888; border-radius: 10px; } .chat-box::-webkit-scrollbar-
thumb:hover { background: #555; }

.user, .bot { max-width: 75%; margin-bottom: 12px; padding: 10px 15px; border-radius: 18px; word-
wrap: break-word; font-size: 15px; line-height: 1.4; clear: both;
32
}
.user {
background: linear-gradient(135deg, #667eea, #764ba2); color: #fff; border-radius: 18px 18px 4px 18px;
float: right;
box-shadow: 0 2px 8px rgba(102,126,234,0.3); animation: slideInRight .3s ease-out;
} .bot { background: #fff; color: #333; border-radius: 18px 18px 18px 4px;
float: left;
box-shadow: 0 2px 8px rgba(0,0,0,0.1); animation: slideInLeft .3s ease-out; white-space: pre-wrap;
}

@keyframesslideInRight{from{opacity:0;transform:translateX(20px);}
to{opacity:1;transform:translateX(0);} }
@keyframesslideInLeft{from{opacity:0;transform:translateX(-20px);}
to{opacity:1;transform:translateX(0);}

.card { border-radius: 20px; border: none; max-width: 800px; margin: 0 auto; } .card-title { font-weight:
bold; font-size: 24px; color: #667eea; background: linear-gradient(135deg,#667eea,#764ba2);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.input-group {
box-shadow: 0 4px 12px rgba(0,0,0,0.1); border-radius: 25px; overflow: hidden; }
.form-control { border: 2px solid #e0e0e0; border-radius: 25px 0 0 25px; padding: 12px 20px; font-size:
15px; transition: .3s;
}
.form-control:focus { border-color: #667eea; box-shadow: 0 0 0 .2rem rgba(102,126,234,.25);
}
.btn-primary {
background: linear-gradient(135deg,#667eea,#764ba2); border: none; border-radius: 0 25px 25px 0;
padding: 12px 30px; font-weight: 600; transition: .3s;
}
.btn-primary:hover {
background: linear-gradient(135deg,#764ba2,#667eea); transform: scale(1.05); box-shadow: 0 4px 12px
rgba(102,126,234,.4);
}
@media (max-width:768px){
.chat-box{height:350px;}
.user,.bot{max-width:85%;font-size:14px;}
.card-title{font-size:20px;}
}

❖ Coding of [Link]
constchatBox=[Link]('chatBox'),chatForm=[Link]('chatForm'),us
erInput=[Link]('userInput'),
botResponses=new Map([
[['hello','hi','hey'],"Hello! How can I help you today?"],
[['how are you'],"I'm just a bot, but I'm doing great! How about you?"],
[['your name','who are you'],"I'm a simple chatbot created with HTML, CSS, and JS."],
[['bye','goodbye'],"Goodbye! Have a nice day!"],
33
[['thank','thanks'],"You're welcome!"],
[['help'],"Ask me about my name, tell a joke, or just chat!"],
[['what can you do'],"I can chat, answer questions, and share fun facts."],
[['joke'],"Why don’t scientists trust atoms? Because they make up everything!"],
[['weather'],"It's always sunny in code-land!"],
[['time'],`It's ${new Date().toLocaleTimeString()}`],
[['date'],`Today is ${new Date().toLocaleDateString()}`],
[['age'],"I'm timeless!"],
[['repeat'],"Sure! What should I repeat?"],
[['bored'],"Let's chat! Want to hear a joke or a fact?"],
[['i love you'],"Aw! I'm just code, but I appreciate you."],
[['color','favorite color'],"Probably #00FF00 — that’s green!"],
[['food','pizza'],"I don’t eat, but I hear pizza’s awesome."],
[['movie'],"I like sci-fi... in theory."],
[['book'],"I recommend 'The Art of Computer Programming'!"],
[['ai','robot'],"Beep boop! I’m friendly and powered by AI!"],
[['2+2'],"2 + 2 = 4"],
[['capital of france'],"The capital of France is Paris."],
[['meaning of life'],"42... according to Hitchhiker’s Guide!"],
[['sleep'],"Nope, I’m available 24/7."],
[['dream'],"Only in binary."],
[['secret'],"I'm powered by code and curiosity."],
[['google'],"Google is great, but I’m cooler "],
[['earth'],"Our beautiful blue planet!"],
[['coffee'],"Programmer fuel! "],
[['good morning'],"Good morning! Have a great day!"],
[['good night'],"Sweet dreams! "],
[['funny'],"I'm not a comedian, but I try! "],
[['animal'],"I like cats and dogs! "],
[['dog'],"Woof! Dogs are awesome! "],
[['cat'],"Meow! Cats are cool! "],
[['python'],"Python is clean and powerful!"],
[['javascript'],"JS makes the web come alive!"],
[['html'],"HTML gives structure!"],
[['css'],"CSS adds style!"],
[['computer'],"My digital home "],
[['game'],"Do you like games? "],
[['music'],"Music and code — perfect combo! "],
[['sports'],"Sports are fun! Which one’s your favorite?"],
[['covid'],"Stay safe and healthy! "],
[['can you help'],"That’s what I’m here for!"]
]),
saveChatHistory=h=>[Link]('chatHistory',[Link](h)),
loadChatHistory=()=>[Link]([Link]('chatHistory')||'[]'),appendMessage=(t,s)=>{const
d=[Link]('div');[Link]=s;[Link]=t;[Link](d);[Link]
p=[Link]},renderChatHistory=h=>{[Link]='';[Link](({text,sender})=>appe
ndMessage(text,sender))},

34
getBotResponse=i=>{constmsg=[Link]().toLowerCase();for(const [keys,res]of
botResponses)if([Link](k=>[Link](k)))return res;return "Sorry, I didn't understand that. Can you
rephrase?";}; let chatHistory=loadChatHistory();
[Link]=()=>{if(![Link]){const greet="Hi! I'm your chatbot. Type 'help' to see what I
cando.";appendMessage(greet,'bot');[Link]({text:greet,sender:'bot'});saveChatHistory(chatHistory
)}else renderChatHistory(chatHistory)}; [Link]('submit',e=>{[Link]();const
userMsg=[Link]();if(!userMsg)return;appendMessage(userMsg,'user');[Link]({text:us
erMsg,sender:'user'});saveChatHistory(chatHistory);[Link]='';setTimeout(()=>{const
botMsg=getBotResponse(userMsg);appendMessage(botMsg,'bot');[Link]({text:botMsg,sender:'bot'
});saveChatHistory(chatHistory)

❖ Coding of [Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SmartBot - AI Chatbot Assistant</title>
<linkhref="[Link] rel="stylesheet">
<link rel="stylesheet" href="styles/[Link]">
</head>
<body class="bg-light">
<div class="container mt-5">
<div class="card shadow-lg">
<div class="card-body">
<h5 class="card-title text-center mb-3"> SmartBot Assistant</h
<div class="chat-box mb-3 p-3 border" id="chatBox"></div>
<form class="input-group mb-2" id="chatForm" autocomplete="off">
<input type="text" class="form-control" id="userInput" placeholder="Type your
message..." required/>
<button class="btn btn-primary" type="submit">Send</button>
</form>
<div class="text-center">
<button class="btn btn-outline-danger btn-sm" id="clearChat"> Clear Chat</button>
</div>
</div>
</div>
</div>
<script src="scripts/[Link]"></script>
</body>
</html>

35
❖ Output:

36
3. Flask IoT Day/Night Detector
This is an Internet of Things (IoT) project that creates a smart, responsive web interface that automatically
adapts its theme based on real-world ambient light conditions. The system uses an LDR (Light Dependent
Resistor) sensor connected to an Arduino board to measure light intensity, transmits this data to a Flask web
server via serial communication, and displays it on a live webpage that dynamically switches between light
and dark themes.

❖ PROJECT STRUCTURE

flaskiotforgit/

├── [Link] # Flask application entry point
├── [Link] # Python package dependencies
├── [Link] # Threading Queue pattern demo
├── [Link] # Project documentation
├── ldr_read/ # Arduino firmware directory
│ └── ldr_read.ino # Arduino sketch for LDR sensor

├── static/ # Static web assets
│ └── [Link] # CSS styling for webpage

└── templates/ # Flask HTML templates
└── [Link]

❖ Coding of ldr_read.ino
const int LDR_PIN = A0;
const int ledPin = 13;
const int BAUD_RATE = 9600;
void setup() {
[Link](BAUD_RATE);
}
void loop() { int ldrValue = analogRead(LDR_PIN);
if (ldrValue < 400) digitalWrite(ledPin, LOW); else digitalWrite(ledPin, HIGH);
[Link](ldrValue); delay(500);
}
❖ Coding of [Link]
body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; height:
100vh; flex-direction: column; } h1 { font-size: 2em; }
#ldr-value { font-size: 5em; font-weight: bold; }
❖ Coding of [Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TecDev Change Theme using LDR Sensor Data</title>
37
<link rel="stylesheet" href="{{ url_for('static', filename='[Link]') }}"/>
</head>
<body>
<h1>LDR Light Sensor Reading</h1>
<div id="ldr-value">Loading...</div>
<script>
// Function to fetch data from the Flask API endpoint
function fetchLdrValue() { fetch('/data').then(response => [Link]())
.then( data => {
[Link]('ldr-value').textContent = data.ldr_value;
// Change background color based on LDR value
if (data.ldr_value > 400) {
[Link] = '#000000'; // Dark theme
[Link] = '#ffffff';
} else {
[Link] = '#ffffff'; // Light theme
[Link] = '#000000';
}
}).catch(error => [Link]('Error fetching data:', error));
}

// Fetch the data initially and then every 1 second


fetchLdrValue();
setInterval(fetchLdrValue, 1000);
</script>
</body>
</html>

❖ Coding of [Link]
from flask import Flask, render_template, jsonify import serial, threading, time from threading import Lock
app = Flask(__name__)
BAUD_RATE = 9600 SERIAL_PORT = 'COM3'
data_lock = Lock() latest_ldr_value = 0 def read_from_serial(): global latest_ldr_value try:
ser = [Link](SERIAL_PORT, BAUD_RATE, timeout=1) [Link](1) print(f"Connected
to Arduino on {SERIAL_PORT}") while True:
line = [Link]().decode('utf-8').strip() if line: try:
value = int(line) with data_lock:
latest_ldr_value = value print(f"Received LDR value: {value}") except
ValueError:
print(f"Invalid data: {line}") [Link](0.5) except [Link] as e:
print(f"Serial error: {e}") [Link](target=read_from_serial, daemon=True).start()
@[Link]('/') def index():
return render_template('[Link]')
@[Link]('/data') def get_data(): with data_lock: value=latest_ldr_value
print(value) return jsonify(ldr_value=value) if __name__ == '__main__':
[Link](host='[Link]', port=5000, debug=False)
❖ [Link]
import threading import time

38
# Create a shared global variable and a lock to protect it data = 0 data_lock = [Link]() def
daemon_worker(): global data while True:
with data_lock: data += 1
[Link](1)
# Start the daemon thread
worker_thread = [Link](target=daemon_worker, daemon=True) worker_thread.start()
# Main thread loop for _ in range(5): with data_lock:
current_data = data print(f"Main thread reads: {current_data}")
[Link](1.5)
❖ [Link]
import threading import queue
import time
# Create a thread-safe queue
data_queue = [Link]()
def daemon_producer():
count = 0 while True: data_queue.put(count)
count += 1
[Link](1)
# Start the daemon thread
producer_thread = [Link](target=daemon_producer, daemon=True) producer_thread.start()
# Main thread loop for _ in range(5):
# Retrieve the latest item from the queue if not data_queue.empty():
current_data = data_queue.get() print(f"Main thread retrieves from queue: {current_data}") else:
print("Queue is empty, waiting for data...") [Link](1.5)

❖ Output:

39
40
41
[Link] Detection System

This project is an intelligent Eye Detection System that tracks the user’s eyes in real time. It automatically puts
the system to sleep when the eyes remain closed for a certain time and enables eye-based scrolling for hands-
free navigation. Built using computer vision techniques, it ensures accurate detection and smooth performance.
The main aim is to enhance human-computer interaction through smart and intuitive control.
❖ Project Structure

c:\eye_detection\
├── [Link]
├── [Link]
├── shape_predictor_68_face_landmarks.dat
├── static/
│ └── [Link]
├── templates/
└── [Link]

❖ Coding of [Link]
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-
serif;
display: flex; justify-content: center; align-items: center; flex-direction: column; height: 100vh;
margin: 0;
background-color: #f0f2f5; color: #333;
}
.video-container { border: 5px solid #ccc; border-radius: 10px; overflow: hidden;
box-shadow: 0 4px 12px rgba(0,0,0,0.15); background-color: #000;
}
img { display: block; width: 100%; max-width: 640px; border-radius: 5px;
}
.instructions { margin-top: 25px; background-color: #fff; padding: 20px;
border-radius: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);
max-width: 600px;
text-align: left;
}
.instructions h2 { margin-top: 0; color: #1c1e21; border-bottom: 1px solid #ddd;
padding-bottom: 10px;
}
.instructions ul { list-style-type: none; padding: 0;
}
.instructions li { margin-bottom: 10px; line-height: 1.5;
}
.instructions li strong { color: #007bff;
}

42
❖ Coding of [Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{{url_for( 'static', filename='[Link]')}}"/>
</head>
<body>
<h1>Eye Movement Control System</h1>
<div class="video-container">
<img src="{{ url_for('video_feed') }}" alt="Video Feed">
</div>
<div class="instructions">
<h2>How to Use</h2> <ul>
<li><strong>Sleep Laptop:</strong> Close your eyes for a few seconds.</li>
<li><strong>Scroll Document:</strong> Look steadily up or down.</li>
<li><strong>Switch Applications:</strong> Look steadily to the left or right.</li>
</ul>
<p><strong>Note:</strong> There is a short cooldown period after each action to prevent accidental
repeats.</p>
</div>
</body>
</html>
❖ Coding of [Link]

import cv2 import dlib import numpy as np


from flask import Flask, render_template, Response from [Link] import distance as dist
import pyautogui import os import platform
import time
app = Flask( name )
# --- Configuration Constants ---
# Path to the facial landmark predictor model
SHAPE_PREDICTOR_PATH = "shape_predictor_68_face_landmarks.dat"
# Eye Aspect Ratio (EAR) constants for blink detection
EYE_AR_THRESH = 0.25
EYE_AR_CONSEC_FRAMES_SLEEP = 40 # Number of frames eye must be closed to trigger sleep
# Gaze detection thresholds and frame counters
GAZE_THRESH_X = 7
GAZE_THRESH_Y = 5
GAZE_CONSEC_FRAMES = 10 # Number of frames gaze must be held to trigger action
43
# --- Global Variables --- # Frame counters for actions sleep_counter = 0 gaze_left_counter = 0
gaze_right_counter = 0 gaze_up_counter = 0
gaze_down_counter = 0
# Cooldown timers to prevent rapid-fire actions last_action_time = 0
ACTION_COOLDOWN = 1.5 # seconds
# Initialize Dlib's face detector (HOG-based) and then create the facial landmark predictor try:
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(SHAPE_PREDICTOR_PATH)
except RuntimeError:
print("Error: The Dlib shape predictor model file 'shape_predictor_68_face_landmarks.dat' was not
found.")
print("Please download it from [Link] print("And
extract it to the same directory as [Link]") exit()
# Grab the indexes of the facial landmarks for the left and right eye
(lStart, lEnd) = (42, 48)
(rStart, rEnd) = (36, 42)

def eye_aspect_ratio(eye):
"""
Computes the eye aspect ratio (EAR) to determine if an eye is closed.
EAR is the ratio of distances between vertical and horizontal eye landmarks.
"""
# Compute the euclidean distances between the two sets of vertical eye landmarks (x, y)-coordinates A =
[Link](eye[1], eye[5]) B = [Link](eye[2], eye[4])
# Compute the euclidean distance between the horizontal eye landmark (x, y)-coordinates C =
[Link](eye[0], eye[3])
# Compute the eye aspect ratio ear = (A + B) / (2.0 * C)
return ear
def get_gaze_direction(eye_points, facial_landmarks):
"""
Calculates the gaze direction by finding the position of the pupil relative to the eye's center.
"""
# Get the bounding box of the eye region

44
eye_region = [Link]([(facial_landmarks.part(point).x, facial_landmarks.part(point).y) for point in
x_min, y_min = [Link](eye_region, axis=0) x_max, y_max = [Link](eye_region, axis=0) eye_center_x =
(x_min + x_max) // 2 eye_center_y = (y_min + y_max) // 2
# Isolate the eye from the frame, convert to grayscale, and find the pupil
gray_eye = [Link](frame[y_min:y_max, x_min:x_max], cv2.COLOR_BGR2GRAY) _, threshold_eye
= [Link](gray_eye, 55, 255, cv2.THRESH_BINARY_INV)
contours, _ = [Link](threshold_eye, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) contours
= sorted(contours, key=lambda x: [Link](x), reverse=True)
if contours:
(x, y, w, h) = [Link](contours[0]) pupil_center_x = x_min + x + w // 2 pupil_center_y = y_min + y
+ h // 2
# Calculate horizontal and vertical gaze ratios gaze_ratio_x = (pupil_center_x - x_min) / (x_max - x_min) if
(x_max - x_min) != 0 else 0.5 gaze_ratio_y = (pupil_center_y - y_min) / (y_max - y_min) if (y_max - y_min)
!= 0 else 0.5
return gaze_ratio_x, gaze_ratio_y, (pupil_center_x, pupil_center_y) return None, None, None
def perform_action(action): """
Executes a system command based on the detected action. Includes a cooldown to prevent repeated actions.
"""
global last_action_time current_time = [Link]() if current_time - last_action_time <
ACTION_COOLDOWN: return # Cooldown active print(f"--- ACTION: {action} ---")
if action == "sleep":
system_os = [Link]().lower() try: if system_os == "windows":
[Link]('win', 'e') # Lock the screen print
#[Link]("[Link] [Link],SetSuspendState 0,1,0") elif system_os == "darwin": # macOS
[Link]("pmset sleepnow")
elif system_os == "linux":
[Link]("systemctl suspend")
except Exception as e:
print(f"Could not put system to sleep: {e}")
elif action == "scroll_up": [Link](100) # Scroll up
elif action == "scroll_down": [Link](-100) # Scroll down
elif action == "switch_app":
[Link]('alt', 'tab') last_action_time = current_time

45
def process_frame(): """
Main generator function to process video frames, detect gestures, and yield frames for streaming.
""" global sleep_counter, gaze_left_counter, gaze_right_counter, gaze_up_counter, gaze_down_counter,
frame
cap = [Link](0) if not [Link]():
print("Error: Could not open webcam.") return
while True:
success, frame = [Link]() if not success:
break
gray = [Link](frame, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 0) # Detect faces in the grayscale frame
# Loop over the face detections for rect in rects:
shape = predictor(gray, rect) shape_np = [Link]((68, 2), dtype="int") for i in range(0, 68): shape_np[i] =
([Link](i).x, [Link](i).y)
# Extract left and right eye coordinates left_eye = shape_np[lStart:lEnd] right_eye = shape_np[rStart:rEnd]
# Calculate Eye Aspect Ratio for both eyes left_ear = eye_aspect_ratio(left_eye) right_ear =
eye_aspect_ratio(right_eye) ear = (left_ear + right_ear) / 2.0
# Draw contours around eyes left_eye_hull = [Link](left_eye) right_eye_hull =
[Link](right_eye) [Link](frame, [left_eye_hull], -1, (0, 255, 0), 1)
[Link](frame, [right_eye_hull], -1, (0, 255, 0), 1) action_text = "STATUS: AWAKE"
# --- 1. SLEEP DETECTION (EYE CLOSE) --- if ear < EYE_AR_THRESH:
sleep_counter += 1 if sleep_counter >= EYE_AR_CONSEC_FRAMES_SLEEP: perform_action("sleep")
sleep_counter = 0 # Reset after action
action_text = "EYES CLOSED" else:
sleep_counter = 0
# --- 2. GAZE DETECTION (LEFT/RIGHT/UP/DOWN) ---
gaze_ratio_x, gaze_ratio_y, pupil_coords = get_gaze_direction(range(rStart, rEnd), shape)
if gaze_ratio_x is not None and gaze_ratio_y is not None:
[Link](frame, pupil_coords, 3, (0, 0, 255), -1)
if gaze_ratio_x < 0.35: # Looking right (camera is mirrored) gaze_left_counter += 1 gaze_right_counter = 0 if
gaze_left_counter >= GAZE_CONSEC_FRAMES:
perform_action("switch_app") gaze_left_counter = 0
action_text = "LOOKING LEFT"

46
elif gaze_ratio_x > 0.65: # Looking left (camera is mirrored) gaze_right_counter += 1 gaze_left_counter = 0 if
gaze_right_counter >= GAZE_CONSEC_FRAMES:
perform_action("switch_app") gaze_right_counter = 0
action_text = "LOOKING RIGHT" else:
gaze_left_counter = 0 gaze_right_counter = 0
if gaze_ratio_y < 0.4: # Looking up gaze_up_counter += 1 gaze_down_counter = 0 if gaze_up_counter >=
GAZE_CONSEC_FRAMES: perform_action("scroll_up") gaze_up_counter = 0
action_text = "LOOKING UP"
elif gaze_ratio_y > 0.6: # Looking down gaze_down_counter += 1 gaze_up_counter = 0 if
gaze_down_counter >= GAZE_CONSEC_FRAMES: perform_action("scroll_down") gaze_down_counter = 0
action_text = "LOOKING DOWN"
gaze_up_counter = 0
gaze_down_counter = 0
# Display text on frame
[Link](frame, f"EAR: {ear:.2f}", (300, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0,
255), 2) [Link](frame, action_text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
# Encode the frame in JPEG format ret, buffer = [Link]('.jpg', frame) frame_bytes = [Link]()
# Yield the frame in the response
yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n')
[Link]()
@[Link]('/') def index():
"""Video streaming home page.""" return render_template('[Link]')
@[Link]('/video_feed') def video_feed():
"""Video streaming route. Put this in the src attribute of an img tag.""" return Response(process_frame(),
mimetype='multipart/x-mixed-replace; boundary=frame')

if name == ' main ':


# Note: Using debug=False is recommended for production.
# Use threaded=True to handle multiple clients, though not strictly necessary here.
[Link](debug=True, threaded=True, use_reloader=False

47
❖ Output:

48
[Link]
This project is a digital portfolio developed to present personal skills, achievements, and
projects in a structured and visually appealing format. It serves as a professional platform that
reflects individual growth, technical expertise, and creativity. The portfolio includes well-
organized sections for education, technical skills, and project showcases, allowing visitors to
easily explore the creator’s work. Designed with a responsive layout and clean interface, it
ensures smooth accessibility across devices. The main goal of this project is to build a strong
personal brand and provide a professional online presence for future opportunities.

❖ Project Structure

My portfolio
├─ [Link] # Main HTML file (provided)
├─ [Link] # Project overview and instructions
├─ .gitignore # Typical ignores (node_modules, .env, etc.)
├─ images/
│ └─ [Link] # Profile image used in [Link]
├─ css/
│ └─ [Link] # Main stylesheet linked from [Link]
├─ js/
│ └─ [Link]

❖ Coding of [Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Yashika Paryani - Portfolio</title>
<link rel="stylesheet" href="[Link]">
<link
href="[Link]
rel="stylesheet">
<link rel="stylesheet" href="[Link]
</head>
<body>
<!-- Navigation -->
<nav class="navbar">
<div class="nav-container">
<div class="nav-logo">
<a href="#home">YP</a>
</div>
<ul class="nav-menu">
<li class="nav-item">
<a href="#home" class="nav-link">Home</a>
</li>
<li class="nav-item">
<a href="#about" class="nav-link">About</a>
</li>
49
<li class="nav-item">
<a href="#experience" class="nav-link">Experience</a>
</li>
<li class="nav-item">
<a href="#projects" class="nav-link">Projects</a>
</li>
<li class="nav-item">
<a href="#skills" class="nav-link">Skills</a>
</li>
<li class="nav-item">
<a href="#contact" class="nav-link">Contact</a>
</li>
</ul>
<div class="hamburger">
<span class="bar"></span>
<span class="bar"></span>
<span class="bar"></span>
</div>
</div>
</nav>

<!-- Hero Section -->


<section id="home" class="hero">
<div class="hero-container">
<div class="hero-content">
<div class="hero-text">
<h1 class="hero-title">
Hi, I'm Yashika Paryani
</h1>
<p class="hero-subtitle">WEB DEVELOPER</p>
<p class="hero-description">
Passionate about creating innovative solutions and turning ideas into reality through code.
</p>
<div class="hero-buttons">
<a href="#projects" class="btn btn-primary">View My Work</a>
<a href="#contact" class="btn btn-secondary">Get In Touch</a>
</div>
</div>
<div class="hero-image">
<div class="profile-image-container">
<img src="[Link]" alt="Yashika Paryani" class="profile-image" id="profileImage">
<div class="image-placeholder" id="imagePlaceholder">
<i class="fas fa-user"></i>
<p>Add your photo here</p>
</div>
</div>
</div>
</div>
</div>
<div class="scroll-indicator">
<div class="scroll-arrow"></div>
</div>
</section>

<!-- About Section -->


50
<section id="about" class="about">
<div class="container">
<h2 class="section-title">About Me</h2>
<div class="about-content">
<div class="about-text">
<p>
A dedicated BCA student with a strong foundation in programming, digital marketing, and
technical writing. Certified in Lego Mindstorms Robotics and IBM's Machine Learning program, with hands-
on experience in Python-based machine learning projects, including a recommendation system and a
prediction system.
</p>
<p>
Passionate about problem-solving and eager to apply my skills in a dynamic environment
while continuously learning and growing.
</p>
<div class="about-stats">
<div class="stat">
<h3>5+</h3>
<p>Projects Completed</p>
</div>
<div class="stat">
<h3>5+</h3>
<p>Technologies</p>
</div>
</div>
</div>
</div>
</div>
</section>

<!-- Experience Section -->


<section id="experience" class="experience">
<div class="container">
<h2 class="section-title">Experience</h2>
<div class="timeline">
<div class="timeline-item">
<div class="timeline-content">
<div class="timeline-header">
<h3>Intern</h3>
<span class="company">Innobimb Infotech Pvt Ltd</span>
<span class="duration">Bhopal, Madhya Pradesh | March 2025 - Present</span>
</div>
<p class="timeline-description">
Here I developed many real-time projects.
</p>
</div>
</div>
</div>
</div>
</section>

<!-- Projects Section -->


<section id="projects" class="projects">
<div class="container">
<h2 class="section-title">Featured Projects</h2>
51
<div class="projects-grid">
<div class="project-card">
<div class="project-image">
<div class="project-placeholder">
<i class="fas fa-calendar-alt"></i>
</div>
</div>
<div class="project-content">
<h3>Event Management System</h3>
<p>Multi-role app (Admin, Coordinator, Audience) for managing events and participants.
Integrated phone OTP verification, like feature, and real-time leaderboard. Complete authentication and
dashboard-based control panel.</p>
<div class="project-tech">
<span class="tech-tag">React</span>
<span class="tech-tag">[Link]</span>
<span class="tech-tag">MongoDB</span>
</div>
</div>
</div>
<div class="project-card">
<div class="project-image">
<div class="project-placeholder">
<i class="fas fa-question-circle"></i>
</div>
</div>
<div class="project-content">
<h3>Real-Time Quiz App</h3>
<p>MERN + Flask + [Link]: Role-based login for Admin and Users, with admin-
controlled quiz flow. Real-time leaderboard, timer, and per-question stats using WebSockets. Hosted frontend
on Netlify and backend on Render.</p>
<div class="project-tech">
<span class="tech-tag">MERN Stack</span>
<span class="tech-tag">Flask</span>
<span class="tech-tag">[Link]</span>
</div>
</div>
</div>
<div class="project-card">
<div class="project-image">
<div class="project-placeholder">
<i class="fas fa-user-check"></i>
</div>
</div>
<div class="project-content">
<h3>Face Recognition System</h3>
<p>Python + OpenCV + face_recognition: Real-time face detection and recognition using a
webcam. Supports marking attendance or authentication using known face data.</p>
<div class="project-tech">
<span class="tech-tag">Python</span>
<span class="tech-tag">OpenCV</span>
<span class="tech-tag">face_recognition</span>
</div>
</div>
</div>
<div class="project-card">
52
<div class="project-image">
<div class="project-placeholder">
<i class="fas fa-heartbeat"></i>
</div>
</div>
<div class="project-content">
<h3>Diabetes Prediction System</h3>
<p>Python + Flask + Machine Learning: Built ML models using Logistic Regression and
Random Forest on the PIMA dataset. Web interface developed with Flask to allow real-time predictions.
Focused on health analytics and user-centric results.</p>
<div class="project-tech">
<span class="tech-tag">Python</span>
<span class="tech-tag">Flask</span>
<span class="tech-tag">Machine Learning</span>
</div>
</div>
</div>
<div class="project-card">
<div class="project-image">
<div class="project-placeholder">
<i class="fas fa-graduation-cap"></i>
</div>
</div>
<div class="project-content">
<h3>College Recommendation System</h3>
<p>Python + Machine Learning: Built using user profiling and feature-based matching
algorithms. Predictive model to recommend suitable colleges to aspirants.</p>
<div class="project-tech">
<span class="tech-tag">Python</span>
<span class="tech-tag">Machine Learning</span>
<span class="tech-tag">Scikit-learn</span>
</div>
</div>
</div>
</div>
</div>
</section>

<!-- Skills Section -->


<section id="skills" class="skills">
<div class="container">
<h2 class="section-title">Skills & Technologies</h2>
<div class="skills-content">
<div class="skills-category">
<h3>Programming Languages</h3>
<div class="skills-grid">
<div class="skill-item">
<i class="fab fa-python"></i>
<span>Python</span>
</div>
<div class="skill-item">
<i class="fab fa-js-square"></i>
<span>JavaScript</span>
</div>
<div class="skill-item">
53
<i class="fab fa-html5"></i>
<span> Basic C++</span>
</div>
<div class="skill-item">
<i class="fab fa-css3-alt"></i>
<span>Basic Java</span>
</div>
</div>
</div>
<div class="skills-category">
<h3>Frameworks & Libraries</h3>
<div class="skills-grid">
<div class="skill-item">
<i class="fab fa-react"></i>
<span>React</span>
</div>
<div class="skill-item">
<i class="fab fa-node-js"></i>
<span>[Link]</span>
</div>
<div class="skill-item">
<i class="fas fa-server"></i>
<span>Flask</span>
</div>
<div class="skill-item">
<i class="fas fa-database"></i>
<span>MongoDB</span>
</div>
</div>
</div>
<div class="skills-category">
<h3>Machine Learning & Tools</h3>
<div class="skills-grid">
<div class="skill-item">
<i class="fas fa-brain"></i>
<span>Machine Learning</span>
</div>
<div class="skill-item">
<i class="fas fa-eye"></i>
<span>OpenCV</span>
</div>
<div class="skill-item">
<i class="fab fa-git-alt"></i>
<span>Git</span>
</div>
<div class="skill-item">
<i class="fas fa-code-branch"></i>
<span>[Link]</span>
</div>
</div>
</div>
</div>
</div>
</section>

54
<!-- Contact Section -->
<section id="contact" class="contact">
<div class="container">
<h2 class="section-title">Get In Touch</h2>
<div class="contact-content">
<div class="contact-info">
<h3>Let's work together!</h3>
<p>I'm always open to discussing new opportunities, interesting projects, or just having a chat
about technology.</p>
<div class="contact-details">
<div class="contact-item">
<i class="fas fa-envelope"></i>
<span>yashikaparyani29@[Link]</span>
</div>
<div class="contact-item">
<i class="fas fa-phone"></i>
<span>+91 9303296024</span>
</div>
<div class="contact-item">
<i class="fas fa-map-marker-alt"></i>
<span>Bhopal, Madhya Pradesh</span>
</div>
</div>
<div class="social-links">
<a href="[Link] class="social-link" target="_blank"
rel="noopener noreferrer"><i class="fab fa-linkedin"></i></a>
</div>
</div>
<form action="[Link] method="POST">
<div class="form-group">
<input type="text" id="name" name="name" placeholder="Your Name" required>
</div>
<div class="form-group">
<input type="email" id="email" name="email" placeholder="Your Email" required>
</div>
<div class="form-group">
<input type="text" id="subject" name="subject" placeholder="Subject" required>
</div>
<div class="form-group">
<textarea id="message" name="message" placeholder="Your Message" rows="5"
required></textarea>
</div>
<button type="submit" class="btn btn-primary">Send Message</button>
</form>
</div>
</div>
</section>

<!-- Footer -->


<footer class="footer">
<div class="container">
<p>&copy; 2025 Yashika Paryani. All rights reserved.</p>
</div>
</footer>

55
<script src="[Link]"></script>
</body>
</html>

❖ Coding of [Link]
:root{
--primary:#2b6ef6;
--bg:#f8f9fb;
--text:#222;
--muted:#666;
}
*{box-sizing:border-box;margin:0;padding:0;font-family: 'Poppins', sans-serif;}
body{background:var(--bg);color:var(--text);line-height:1.5;}
.navbar{display:flex;align-items:center;justify-content:space-between;padding:1rem
2rem;background:#fff;box-shadow:0 2px 8px rgba(0,0,0,0.05)}
.nav-logo a{font-weight:700;color:var(--primary);text-decoration:none}
.nav-menu{display:flex;gap:1rem;list-style:none}
.nav-menu a{text-decoration:none;color:var(--text);padding:.4rem .6rem;border-radius:6px}
.hamburger{display:none;cursor:pointer;flex-direction:column;gap:4px}
.hamburger span{width:24px;height:3px;background:#333;border-radius:2px}
/* Hero */
.hero{display:flex;align-items:center;gap:2rem;padding:4rem 2rem}
.hero-text h1{font-size:2rem;margin-bottom:.5rem}
.hero-subtitle{letter-spacing:3px;color:var(--muted);margin-bottom:1rem}
.hero-image{max-width:220px}
.image-placeholder{display:none;align-items:center;justify-content:center;border-
radius:50%;background:#e9eefc;height:200px;width:200px;color:var(--muted)}
/* Projects grid */
.projects-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:1.25rem;padding:2rem 0}
/* Responsive */
@media (max-width:900px){
.projects-grid{grid-template-columns:repeat(2,1fr)}
}
@media (max-width:700px){
.nav-menu{display:none}
.hamburger{display:flex}
.hero{flex-direction:column;text-align:center}
.projects-grid{grid-template-columns:1fr}

#profileImage{display:none}

❖ Coding of [Link]
// Mobile Navigation Toggle
const hamburger = [Link]('.hamburger');
const navMenu = [Link]('.nav-menu');

[Link]('click', () => {
56
[Link]('active');
[Link]('active');
});

// Close mobile menu when clicking on a link


[Link]('.nav-link').forEach(n => [Link]('click', () => {
[Link]('active');
[Link]('active');
}));

// Smooth scrolling for navigation links


[Link]('a[href^="#"]').forEach(anchor => {
[Link]('click', function (e) {
[Link]();
const target = [Link]([Link]('href'));
if (target) {
[Link]({
behavior: 'smooth',
block: 'start'
});
}
});
});

// Navbar background change on scroll


[Link]('scroll', () => {
const navbar = [Link]('.navbar');
if ([Link] > 100) {
[Link] = 'rgba(255, 255, 255, 0.98)';
[Link] = '0 2px 20px rgba(0, 0, 0, 0.15)';
} else {
[Link] = 'rgba(255, 255, 255, 0.95)';
[Link] = '0 2px 20px rgba(0, 0, 0, 0.1)';
}
});

// Active navigation link highlighting


[Link]('scroll', () => {
const sections = [Link]('section[id]');
const navLinks = [Link]('.nav-link');

let current = '';


[Link](section => {
const sectionTop = [Link];
const sectionHeight = [Link];
if ([Link] >= (sectionTop - 200)) {
current = [Link]('id');
}
});

[Link](link => {
[Link]('active');
if ([Link]('href') === `#${current}`) {
[Link]('active');
}
57
});
});

// Intersection Observer for animations


const observerOptions = {
threshold: 0.1,
rootMargin: '0px 0px -50px 0px'
};

const observer = new IntersectionObserver((entries) => {


[Link](entry => {
if ([Link]) {
[Link]('fade-in-up');
}
});
}, observerOptions);

// Observe elements for animation


[Link]('DOMContentLoaded', () => {
const animateElements = [Link]('.timeline-item, .project-card, .skill-item, .stat');
[Link](el => [Link](el));
});

// Contact form handling


const contactForm = [Link]('.contact-form');
if (contactForm) {
[Link]('submit', (e) => {
[Link]();

// Get form data


const formData = new FormData(contactForm);
const name = [Link]('name');
const email = [Link]('email');
const subject = [Link]('subject');
const message = [Link]('message');

// Simple validation
if (!name || !email || !subject || !message) {
alert('Please fill in all fields');
return;
}

// Email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (![Link](email)) {
alert('Please enter a valid email address');
return;
}

// Here you would typically send the form data to a server


// For now, we'll just show a success message
alert('Thank you for your message! I will get back to you soon.');
[Link]();
});
}
58
// Profile image handling
const profileImage = [Link]('profileImage');
const imagePlaceholder = [Link]('imagePlaceholder');

// Function to handle profile image upload


function handleProfileImageUpload() {
const input = [Link]('input');
[Link] = 'file';
[Link] = 'image/*';
[Link] = (e) => {
const file = [Link][0];
if (file) {
const reader = new FileReader();
[Link] = (e) => {
[Link] = [Link];
[Link] = 'block';
[Link] = 'none';
};
[Link](file);
}
};
[Link]();
}

// Add click event to image placeholder


if (imagePlaceholder) {
[Link]('click', handleProfileImageUpload);
}

// Typing animation for hero title


function typeWriter(element, text, speed = 100) {
let i = 0;
[Link] = '';

function type() {
if (i < [Link]) {
[Link] += [Link](i);
i++;
setTimeout(type, speed);
}
}
type();
}

// Initialize typing animation when page loads


[Link]('DOMContentLoaded', () => {
const heroTitle = [Link]('.hero-title');
if (heroTitle) {
const originalText = [Link];
setTimeout(() => {
typeWriter(heroTitle, originalText, 50);
}, 1000);
}
});
59
// Project card hover effects
[Link]('.project-card').forEach(card => {
[Link]('mouseenter', () => {
[Link] = 'translateY(-10px) scale(1.02)';
});

[Link]('mouseleave', () => {
[Link] = 'translateY(0) scale(1)';
});
});

// Skill item hover effects


[Link]('.skill-item').forEach(item => {
[Link]('mouseenter', () => {
[Link] = 'translateY(-5px) scale(1.05)';
});

[Link]('mouseleave', () => {
[Link] = 'translateY(0) scale(1)';
});
});

// Parallax effect for hero section


[Link]('scroll', () => {
const scrolled = [Link];
const hero = [Link]('.hero');
if (hero) {
const rate = scrolled * -0.5;
[Link] = `translateY(${rate}px)`;
}
});

// Loading animation
[Link]('load', () => {
[Link]('loaded');
});

// Add loading class to body


[Link]('loading');

// Utility function to check if element is in viewport


function isInViewport(element) {
const rect = [Link]();
return (
[Link] >= 0 &&
[Link] >= 0 &&
[Link] <= ([Link] || [Link]) &&
[Link] <= ([Link] || [Link])
);
}

// Add scroll-triggered animations


[Link]('scroll', () => {
const elements = [Link]('.fade-in-up');
60
[Link](element => {
if (isInViewport(element)) {
[Link] = '1';
[Link] = 'translateY(0)';
}
});
});

// Initialize tooltips for project links


[Link]('.project-link').forEach(link => {
[Link]('mouseenter', (e) => {
const tooltip = [Link]('div');
[Link] = 'tooltip';
[Link] = [Link];
[Link] = `
position: absolute;
background: #333;
color: white;
padding: 5px 10px;
border-radius: 5px;
font-size: 12px;
z-index: 1000;
pointer-events: none;
`;
[Link](tooltip);

const rect = [Link]();


[Link] = [Link] + ([Link] / 2) - ([Link] / 2) + 'px';
[Link] = [Link] - [Link] - 5 + 'px';
});

[Link]('mouseleave', () => {
const tooltip = [Link]('.tooltip');
if (tooltip) {
[Link]();
}
});
});

61
❖ Output

62
63
5. Fees Collection & Receipt System

This project automates the process of managing student fee payments. It allows recording of fee transactions,
generating digital receipts, and maintaining a structured database of all payments. The system calculates total
fees, balances, and generates printable receipts for students. Python is used for the software interface, while a
database backend ensures accurate record-keeping. This project streamlines fee management, reduces manual
errors, and provides a reliable and user-friendly solution for educational institutions.

❖ Project Structure
fees_structure/

├── backend/ # Flask REST API Server
│ ├── [Link] # Main Flask application
│ ├── [Link] # SQLAlchemy database models
│ ├── [Link] # Python dependencies
│ ├── fees_collection.db # SQLite database file

└── frontend/ # React + TypeScript UI
├── src/ # Source code directory
│ ├── components/ # Reusable React components
│ │ ├── [Link] # Login form component
│ │ ├── [Link] # Admin control panel
│ │ ├── [Link] # Accountant interface
│ │ ├── [Link] # Student view dashboard
│ │ └── [Link] # Payment form
│ │
│ ├── pages/ # Full page components
│ │ ├── [Link] # Main dashboard page
│ │ └── [Link] # Fees collection page
│ │
│ ├── contexts/ # React Context providers
│ │ ├── [Link] # Authentication context
│ │ └── [Link] # Auth types
│ │
│ ├── services/ # API integration layer
│ │ ├── [Link] # HTTP client & API calls
│ │ ├── [Link] # Notification service
│ │ └── [Link] # Permission checking logic
│ │
│ ├── hooks/ # Custom React hooks
│ │ └── [Link] # Authentication hoo
│ │
│ ├── types/ # TypeScript type definitions
│ │ ├── [Link] # API response types
│ │ └── [Link] # Exported types
│ │
│ ├── utils/ # Utility functions
│ │ └── [Link] # Helper functions
│ │
│ ├── styles/ # Component-specific CSS
│ │ └──[Link]
│ ├── [Link] # Root React component
│ ├── [Link] # Global app styles
│ ├── [Link] # React entry point
│ └── [Link] # Global CSS

├── node_modules/ # NPM dependencies
├── [Link] # NPM configuration
├── [Link] # NPM lock file
├── [Link] # Vite build configuration
├── [Link] # TypeScript base config
├── [Link] # ESLint configuration
├── [Link] # HTML entry point
├── .gitignore # Git ignore rules
└── [Link] # Frontend documentation

64
❖ Coding of [Link]
from . import db from datetime import datetime
class Payment([Link]):
id = [Link]([Link], primary_key=True) enrollment = [Link]([Link](50), nullable=False)
student_name = [Link]([Link](100), nullable=False) course = [Link]([Link](50),
nullable=False) installment_number = [Link]([Link](1), nullable=False) amount =
[Link]([Link], nullable=False) payment_mode = [Link]([Link](10), nullable=False)
payment_date = [Link]([Link], nullable=False, default=[Link])
def to_dict(self): return {
'id': [Link],
'enrollment': [Link],
'student_name': self.student_name,
'course': [Link],
'year': [Link],
'installment_number': self.installment_number,
'amount': [Link],
'payment_mode': self.payment_mode,
'payment_date': self.payment_date.isoformat()
}
❖ Coding of [Link]

from flask import Flask, request, jsonify


from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Numeric
from [Link] import generate_password_hash, check_password_hash
from datetime import datetime
import os

app = Flask(__name__)
CORS(app)

# Database configuration
basedir = [Link]([Link](__file__))
[Link]['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{[Link](basedir, "fees_collection.db")}'
[Link]['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
[Link]['SECRET_KEY'] = 'your-secret-key-here'

db = SQLAlchemy(app)

# Database Models
class User([Link]):
__tablename__ = 'users'

userid = [Link]([Link], primary_key=True, autoincrement=True)


username = [Link]([Link](50), unique=True, nullable=False)
password = [Link]([Link](255), nullable=False) # Hashed password
userType = [Link]([Link]('Admin', 'Student', 'Accountant', name='user_types'), nullable=False)

def __repr__(self):
return f'<User {[Link]}>'

65
class Student([Link]):
__tablename__ = 'students'

enrollment = [Link]([Link](20), primary_key=True)


name = [Link]([Link](100), nullable=False)
course = [Link]([Link](50), nullable=False)
year = [Link]([Link](20), nullable=False)
mobileNumber = [Link]([Link](15), nullable=False)
fatherName = [Link]([Link](100), nullable=True)
motherName = [Link]([Link](100), nullable=True)
address = [Link]([Link], nullable=True)
userid = [Link]([Link], [Link]('[Link]'), nullable=True) # Link to user account

# Relationships
payments = [Link]('Payment', backref='student_info', lazy=True)
user = [Link]('User', backref='student_profile', lazy=True)

def __repr__(self):
return f'<Student {[Link]} - {[Link]}>'

class Payment([Link]):
__tablename__ = 'payments'

# Composite primary key


receiptNumber = [Link]([Link](20), primary_key=True)
enrollment = [Link]([Link](20), [Link]('[Link]'), primary_key=True)
installmentNumber = [Link]([Link], primary_key=True) # 1 or 2
course = [Link]([Link](50), primary_key=True)
year = [Link]([Link](20), primary_key=True)

# Other columns
dated = [Link]([Link], nullable=False, default=[Link])
amount = [Link](Numeric(10, 2), nullable=False)
paymentMode = [Link]([Link]('CASH', 'CARD', 'UPI', 'CHEQUE', name='payment_modes'),
nullable=False)
userid = [Link]([Link], [Link]('[Link]'), nullable=False)

# Relationships
user = [Link]('User', backref='processed_payments')

def __repr__(self):
return f'<Payment {[Link]} - {[Link]}>'

# Create tables
with app.app_context():
db.create_all()

# Create default admin user if not exists


if not [Link].filter_by(username='admin').first():
admin_user = User(
username='admin',
password=generate_password_hash('admin123'),
userType='Admin'

66
)
[Link](admin_user)
[Link]()
print("Default admin user created: username=admin, password=admin123")

# Create sample student and user data if not exists


if not [Link].filter_by(enrollment='ENR001').first():
# Create student user
student_user = User(
username='student001',
password=generate_password_hash('student123'),
userType='Student'
)
[Link](student_user)
[Link]()

# Create student record


sample_student = Student(
enrollment='ENR001',
name='John Doe',
course='Computer Science',
year='2024-25',
mobileNumber='9876543210',
fatherName='Robert Doe',
motherName='Jane Doe',
address='123 Main Street, City, State - 123456',
userid=student_user.userid
)
[Link](sample_student)
[Link]()
print("Sample student created: enrollment=ENR001, username=student001, password=student123")

# Create sample payment


from datetime import datetime
sample_payment = Payment(
receiptNumber='RCP001',
enrollment='ENR001',
installmentNumber=1,
course='Computer Science',
year='2024-25',
dated=[Link](),
amount=25000,
paymentMode='CASH',
userid=student_user.userid
)
[Link](sample_payment)
[Link]()
print("Sample payment created for ENR001")

# Create accountant user if not exists


if not [Link].filter_by(username='accountant').first():
accountant_user = User(
username='accountant',

67
password=generate_password_hash('acc123'),
userType='Accountant'
)
[Link](accountant_user)
[Link]()
print("Default accountant user created: username=accountant, password=acc123")

@[Link]('/api/health', methods=['GET'])
def health_check():
return jsonify({'status': 'healthy', 'message': 'Fees Collection API is running'})

@[Link]('/api/login', methods=['POST'])
def login():
try:
data = request.get_json()
username = [Link]('username')
password = [Link]('password')

if not username or not password:


return jsonify({'success': False, 'message': 'Username and password required'}), 400

user = [Link].filter_by(username=username).first()

if user and check_password_hash([Link], password):


return jsonify({
'success': True,
'user': {
'userid': [Link],
'username': [Link],
'userType': [Link]
},
'message': 'Login successful'
})
else:
return jsonify({'success': False, 'message': 'Invalid credentials'}), 401

except Exception as e:
return jsonify({'success': False, 'message': str(e)}), 500

@[Link]('/api/students', methods=['GET', 'POST'])


def handle_students():
if [Link] == 'GET':
try:
students = [Link]()
students_list = []
for student in students:
students_list.append({
'enrollment': [Link],
'name': [Link],
'course': [Link],
'year': [Link],
'mobileNumber': [Link],
'fatherName': [Link],

68
'motherName': [Link],
'address': [Link]
})
return jsonify({'success': True, 'data': students_list})
except Exception as e:
return jsonify({'success': False, 'message': str(e)}), 500

elif [Link] == 'POST':


try:
data = request.get_json()

# Check if student already exists


existing_student = [Link].filter_by(enrollment=data['enrollment']).first()
if existing_student:
return jsonify({'success': False, 'message': 'Student with this enrollment already exists'}), 400

student = Student(
enrollment=data['enrollment'],
name=data['name'],
course=data['course'],
year=data['year'],
mobileNumber=data['mobileNumber'],
fatherName=[Link]('fatherName'),
motherName=[Link]('motherName'),
address=[Link]('address')
)

[Link](student)
[Link]()

return jsonify({'success': True, 'message': 'Student added successfully'})

except Exception as e:
[Link]()
return jsonify({'success': False, 'message': str(e)}), 500

@[Link]('/api/payments', methods=['GET', 'POST'])


def handle_payments():
if [Link] == 'GET':
try:
enrollment = [Link]('enrollment')
if enrollment:
payments = [Link].filter_by(enrollment=enrollment).all()
else:
payments = [Link]()

payments_list = []
for payment in payments:
payments_list.append({
'receiptNumber': [Link],
'dated': [Link]('%Y-%m-%d'),
'enrollment': [Link],
'course': [Link],

69
'year': [Link],
'installmentNumber': [Link],
'amount': [Link],
'paymentMode': [Link],
'userid': [Link]
})
return jsonify({'success': True, 'data': payments_list})
except Exception as e:
return jsonify({'success': False, 'message': str(e)}), 500

elif [Link] == 'POST':


try:
data = request.get_json()

# Generate receipt number


last_payment = [Link].order_by([Link]()).first()
if last_payment:
last_num = int(last_payment.receiptNumber)
receipt_number = str(last_num + 1).zfill(8)
else:
receipt_number = "25102156" # Starting receipt number as shown in the image

payment = Payment(
receiptNumber=receipt_number,
dated=[Link](),
enrollment=data['enrollment'],
course=data['course'],
year=data['year'],
installmentNumber=data['installmentNumber'],
amount=data['amount'],
paymentMode=data['paymentMode'],
userid=data['userid']
)

[Link](payment)
[Link]()

return jsonify({
'success': True,
'message': 'Payment recorded successfully',
'receiptNumber': receipt_number
})

except Exception as e:
[Link]()
return jsonify({'success': False, 'message': str(e)}), 500

@[Link]('/api/receipt/<receipt_number>', methods=['GET'])
def get_receipt(receipt_number):
"""Get receipt details by receipt number"""
try:
# Find the payment by receipt number
payment = [Link].filter_by(receiptNumber=receipt_number).first()

70
if not payment:
return jsonify({'success': False, 'message': 'Receipt not found'}), 404

# Get student details


student = [Link].filter_by(enrollment=[Link]).first()

if not student:
return jsonify({'success': False, 'message': 'Student not found'}), 404

# Prepare receipt data


receipt_data = {
'receiptNumber': [Link],
'dated': [Link],
'student': {
'enrollment': [Link],
'name': [Link],
'course': [Link],
'year': [Link],
'mobileNumber': [Link],
'fatherName': [Link],
'motherName': [Link],
'address': [Link]
},
'payment': {
'receiptNumber': [Link],
'dated': [Link],
'enrollment': [Link],
'course': [Link],
'year': [Link],
'installmentNumber': [Link],
'amount': float([Link]),
'paymentMode': [Link],
'userid': [Link]
}
}

return jsonify({'success': True, 'data': receipt_data})

except Exception as e:
return jsonify({'success': False, 'message': str(e)}), 500

@[Link]('/api/payments/<enrollment>', methods=['GET'])
def get_student_payments(enrollment):
"""Get all payments for a specific student"""
try:
# Check if student exists
student = [Link].filter_by(enrollment=enrollment).first()
if not student:
return jsonify({'success': False, 'message': 'Student not found'}), 404

# Get all payments for the student


payments = [Link].filter_by(enrollment=enrollment).order_by([Link]()).all()

71
payments_list = []
for payment in payments:
payments_list.append({
'receiptNumber': [Link],
'dated': [Link],
'course': [Link],
'year': [Link],
'installmentNumber': [Link],
'amount': float([Link]),
'paymentMode': [Link]
})

return jsonify({
'success': True,
'data': {
'student': {
'enrollment': [Link],
'name': [Link],
'course': [Link],
'year': [Link],
'mobileNumber': [Link],
'fatherName': [Link],
'motherName': [Link],
'address': [Link]
},
'payments': payments_list
}
})

except Exception as e:
return jsonify({'success': False, 'message': str(e)}), 500

@[Link]('/api/student/profile', methods=['GET'])
def get_student_profile():
"""Get student profile and payments for authenticated student user"""
try:
# In a real app, you'd get the userid from JWT token or session
# For now, we'll expect it as a query parameter
userid = [Link]('userid')
if not userid:
return jsonify({'success': False, 'message': 'User ID is required'}), 400

# Find student by userid


student = [Link].filter_by(userid=int(userid)).first()
if not student:
return jsonify({'success': False, 'message': 'Student profile not found'}), 404

# Get all payments for the student


payments =
[Link].filter_by(enrollment=[Link]).order_by([Link]()).all()

payments_list = []

72
for payment in payments:
payments_list.append({
'receiptNumber': [Link],
'dated': [Link],
'course': [Link],
'year': [Link],
'installmentNumber': [Link],
'amount': float([Link]),
'paymentMode': [Link]
})

return jsonify({
'success': True,
'data': {
'student': {
'enrollment': [Link],
'name': [Link],
'course': [Link],
'year': [Link],
'mobileNumber': [Link],
'fatherName': [Link],
'motherName': [Link],
'address': [Link]
},
'payments': payments_list
}
})

except Exception as e:
return jsonify({'success': False, 'message': str(e)}), 500

@[Link]('/api/analytics/dashboard', methods=['GET'])
def get_dashboard_analytics():
"""Get dashboard analytics for admin"""
try:
# Total students
total_students = [Link]()

# Total payments
total_payments = [Link]()

# Total amount collected


total_amount = [Link]([Link]([Link])).scalar() or 0

# Payments by mode
payment_modes = [Link](
[Link],
[Link]([Link]),
[Link]([Link])
).group_by([Link]).all()
@[Link]('/api/payment-reminders', methods=['GET'])
def get_payment_reminders():
try:

73
# Get students with pending payments
pending_payments = [Link](
[Link],
[Link],
[Link],
Student.total_fees,
[Link]([Link]([Link]), 0).label('paid_amount'),
[Link]([Link]).label('last_payment_date')
).outerjoin(Payment).group_by(
[Link], [Link], [Link], Student.total_fees
).having(
Student.total_fees > [Link]([Link]([Link]), 0)
).all()

reminders = []
for enrollment, name, course, total_fees, paid_amount, last_payment_date in pending_payments:
pending_amount = total_fees - paid_amount

# Determine reminder type based on business logic


reminder_type = 'partial' if paid_amount > 0 else 'overdue'

# For demo purposes, mark some as upcoming


if pending_amount < total_fees * 0.3: # Less than 30% remaining
reminder_type = 'upcoming'

[Link]({
'studentId': enrollment,
'studentName': name,
'course': course,
'totalFees': float(total_fees),
'paidAmount': float(paid_amount),
'pendingAmount': float(pending_amount),
'type': reminder_type,
'lastPaymentDate': last_payment_date.strftime('%Y-%m-%d') if last_payment_date else None
})

return jsonify({'success': True, 'data': reminders})

except Exception as e:
return jsonify({'success': False, 'message': str(e)}), 500

@[Link]('/api/send-reminder', methods=['POST'])
def send_payment_reminder():
try:
data = request.get_json()
enrollment = [Link]('studentId') # Frontend sends as studentId but we use it as enrollment

if not enrollment:
return jsonify({'success': False, 'message': 'Student ID is required'}), 400

# Get student details


student = [Link].filter_by(enrollment=enrollment).first()
if not student:

74
return jsonify({'success': False, 'message': 'Student not found'}), 404
return jsonify({
'success': True,
'message': f'Payment reminder sent to {[Link]}'
})
if __name__ == '__main__':
[Link](debug=True, port=5000)
❖ Coding of [Link]
from app import create_app
app = create_app()
if _name _== ' _main _':
[Link](debug=True, host='[Link]')
❖ Coding of [Link]
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/[Link]" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vite + React +
TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/[Link]">
</script>
</body>
</html>
❖ Coding of [Link]

import React, { useState, useEffect } from 'react';


import { useAuth } from '../hooks/useAuth';
import { usePaymentReminders } from '../hooks/usePaymentReminders';
import { apiService } from '../services/api';
import '../styles/[Link]';

interface DashboardAnalytics {
summary: {
totalStudents: number;
totalPayments: number;
totalAmount: number;
averagePayment: number;
};
paymentModes: Array<{
mode: string;
count: number;
amount: number;
}>;
courseBreakdown: Array<{
course: string;
count: number;
amount: number;
75
}>;
monthlyCollections: Array<{
month: number;
amount: number;
}>;
recentPayments: Array<{
receiptNumber: string;
studentName: string;
enrollment: string;
amount: number;
paymentMode: string;
dated: string;
course: string;
year: string;
}>;
}

const AdminDashboard: [Link] = () => {


const { user } = useAuth();
const { reminders, loading: remindersLoading } = usePaymentReminders();
const [analytics, setAnalytics] = useState<DashboardAnalytics | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');

useEffect(() => {
if (user?.userType === 'Admin') {
loadAnalytics();
}
}, [user]);

const loadAnalytics = async () => {


try {
setLoading(true);
const response = await [Link]<DashboardAnalytics>('/analytics/dashboard');

if ([Link] && [Link]) {


setAnalytics([Link]);
setError('');
} else {
setError([Link] || 'Failed to load analytics');
}
} catch (err) {
setError('Error loading dashboard data');
[Link]('Analytics error:', err);
} finally {
setLoading(false);
}
};

const formatCurrency = (amount: number): string => {


return new [Link]('en-IN', {
style: 'currency',
currency: 'INR'

76
}).format(amount);
};

const formatDate = (dateString: string): string => {


return new Date(dateString).toLocaleDateString('en-IN');
};

const getMonthName = (month: number): string => {


const months = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
];
return months[month - 1] || '';
};

if (user?.userType !== 'Admin') {


return (
<div className="access-denied">
<h2>Access Denied</h2>
<p>This page is only accessible to Admin users.</p>
</div>
);
}

if (loading) {
return (
<div className="loading-container">
<div className="loading-spinner">Loading analytics...</div>
</div>
);
}

❖ Output:

77
78
Conclusion

In conclusion, the successful implementation of these projects highlights the versatility of


Python and modern web frameworks in solving diverse real-world problems:

1. Flashcard Learn: This project utilizes Generative AI to create a dynamic educational


tool. By integrating the Google Gemini API, it automates the creation of study
materials, providing a personalized and efficient learning experience.

2. Chatbot: This project focuses on building an intelligent chatbot capable of


understanding user queries and providing relevant responses. By integrating Natural
Language Processing (NLP) techniques, it enhances user interaction and automates
communication effectively.

3. Flask IoT Day/Night Detector: This project combines IoT concepts and Flask to create
a system that connects backend logic with web applications. It enables real-time state
monitoring through Flask APIs, showcasing the integration of IoT-style logic with
modern web frameworks.

4. Eye Detection System: This project uses OpenCV and computer vision techniques to
detect and track eyes in real time. It can be applied in security systems, attention
tracking, and accessibility solutions, demonstrating the power of image processing.

5. Portfolio: The portfolio project serves as a personal website to showcase skills,


projects, and achievements. It demonstrates web development proficiency, including
front-end design, back-end integration, and responsive UI development.

6. Fees Collection & Receipt System: This system simplifies the process of collecting
fees and generating receipts digitally. Using database connectivity, it securely stores
student records and automates financial transactions, ensuring transparency and
efficiency.

Collectively, these projects represent a comprehensive exploration of the modern software


development lifecycle. From designing intuitive user interfaces to architecting complex
backend logic and integrating cutting-edge AI services, this journey has bridged the gap
between theoretical knowledge and practical application. It has equipped us with the necessary
tools to tackle real-world challenges, emphasizing the importance of adaptability, full-stack
proficiency, and continuous learning in the rapidly evolving tech landscape.

79
REFERENCES/BIBLIOGRAPHY/WEBIOGRAPHY

• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
python/amp/
• [Link]
• [Link]
python-programmingS
• [Link]
• [Link]
• [Link]
• [Link]
• [Link] – Official Google Generative AI documentation
• [Link] – Research and advancements in Generative
AI
• [Link] – Open-source platform for AI and NLP models
• [Link] – Official React documentation for modern web
development
• [Link] – MDN Web Docs: HTML, CSS, and
JavaScript guides
• [Link] – Official Flask web framework
documentation
• [Link] – Machine learning and AI development
framework
• [Link] – API documentation for GPT models
and GenAI integration
• [Link] – Modern Web APIs
and browser tools
• [Link] – Comprehensive tutorials for web
technologies
• [Link] – Articles and research on AI, ML, and
web technologies • [Link] – Learning
resources for AI and data science.

80
81

Common questions

Powered by AI

The system ensures secure email sending by requiring the configuration of the sender email and an app-specific password generated from a Google Account with 2FA enabled . The email is then sent using SMTP with TLS encryption to provide security during transmission .

The chatbot ensures conversation continuity by storing chat history using `localStorage`, which allows the bot to load previous messages and maintain conversational context. This approach allows it to provide coherent interactions even after page reloads .

The system queries the database for summaries, such as total students, payments, and collected amounts. It aggregates payment data by mode to facilitate analytics, which helps administer understanding of overall financial health at a glance ().

The Flask-based system supports administrative duties by using SQLAlchemy models to manage student records, which involve storing and retrieving detailed information, such as course, payment history, and personal data. It also enables CRUD operations, ensuring comprehensive management of student information .

CSS is used to style email templates, ensuring a readable and visually appealing layout with elements like varying font sizes, colors, and spacing, which enhances user experience and preserves brand identity in communication .

Theme adaptation is implemented using JavaScript that changes webpage styles based on LDR values to adjust to the ambient light. A potential limitation could be the delay in data transmission from the LDR to the server, which might result in slower theme transitions and less seamless user experience .

The fee management system utilizes SQLAlchemy for user authentication, securing passwords through hashing (using Flask's Werkzeug library) and identifying user roles with predefined enumerations such as 'Admin', 'Student', and 'Accountant'. This approach ensures that different roles have specific access privileges, enhancing security .

The chatbot uses Natural Language Processing (NLP) techniques and Machine Learning models to process queries. It is embedded within a Flask web application, allowing it to understand user queries and provide context-aware responses based on pre-trained data .

The IoT project uses a Light Dependent Resistor (LDR) connected to an Arduino to measure light intensity. The data is sent to a Flask server to dynamically switch the webpage theme between light and dark depending on the ambient light conditions measured by the LDR, thus creating a responsive web interface .

The system generates a 6-digit OTP using the Python `random.choices` method to select digits, ensuring a simple yet effective OTP generation mechanism. A potential limitation is the reliance on randomness; without additional entropy or cryptographic methods, OTPs might eventually be predictable over numerous generations .

You might also like