Python File 3rd Yr
Python File 3rd Yr
AN APPRENTICESHIP REPORT
ON
“ Modern WebTech & GenAI ”
SUBMITTED TO
YASHIKA PARYANI
1
SANT HIRDARAM GIRLS COLLEGE, BHOPAL
CERTIFICATE
This is to certify that the work embodies in this apprenticeship work entitled
Supervisor :
Prof. Manju Devnani
(Computer Science Dept)
2
CERTIFICATE
3
ACKNOWLEDGEMENT
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
5
ABSTRACT
6
INDEX
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
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.
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.
9
SYSTEM REQUIREMENTS
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.
❖ 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 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]
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()})
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()
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')
}
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
result = verify_token(token)
if not result['success']:
return jsonify({'error': result['error']}), 401
return decorated_function
def get_current_user():
"""
Get current user from request context
"""
return getattr(request, 'current_user', None)
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
18
// Auto-login check on app startup
checkAutoLogin: async () => {
const token = [Link]();
if (!token) return null;
*{
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;
}
.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;
}
.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-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);
}
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
class GmailService:
def __init__(self):
self.sender_email = [Link]('SENDER_EMAIL')
self.app_name = [Link]('APP_NAME', 'FlashLearn')
def generate_otp(self):
"""Generate a 6-digit OTP"""
return ''.join([Link]([Link], k=6))
# 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>
<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'))
# 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>
<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>
<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)
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)}"
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));
}
❖ 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]
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')
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>
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>
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');
});
[Link](link => {
[Link]('active');
if ([Link]('href') === `#${current}`) {
[Link]('active');
}
57
});
});
// Simple validation
if (!name || !email || !subject || !message) {
alert('Please fill in all fields');
return;
}
// Email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if () {
alert('Please enter a valid email address');
return;
}
function type() {
if (i < [Link]) {
[Link] += [Link](i);
i++;
setTimeout(type, speed);
}
}
type();
}
[Link]('mouseleave', () => {
[Link] = 'translateY(0) scale(1)';
});
});
[Link]('mouseleave', () => {
[Link] = 'translateY(0) scale(1)';
});
});
// Loading animation
[Link]('load', () => {
[Link]('loaded');
});
[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]
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'
def __repr__(self):
return f'<User {[Link]}>'
65
class Student([Link]):
__tablename__ = 'students'
# 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'
# 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()
66
)
[Link](admin_user)
[Link]()
print("Default admin user created: username=admin, password=admin123")
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')
user = [Link].filter_by(username=username).first()
except Exception as e:
return jsonify({'success': False, 'message': str(e)}), 500
68
'motherName': [Link],
'address': [Link]
})
return jsonify({'success': True, 'data': students_list})
except Exception as e:
return jsonify({'success': False, 'message': str(e)}), 500
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]()
except Exception as e:
[Link]()
return jsonify({'success': False, 'message': str(e)}), 500
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
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
if not student:
return jsonify({'success': False, 'message': 'Student not found'}), 404
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
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
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]()
# 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
[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
})
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
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]
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;
}>;
}
useEffect(() => {
if (user?.userType === 'Admin') {
loadAnalytics();
}
}, [user]);
76
}).format(amount);
};
if (loading) {
return (
<div className="loading-container">
<div className="loading-spinner">Loading analytics...</div>
</div>
);
}
❖ Output:
77
78
Conclusion
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.
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.
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
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 .