0% found this document useful (0 votes)
14 views48 pages

Final 3

The document is a mini project report on the 'AI Medical Assistant' developed by Shikhar Singh as part of his Bachelor of Technology in Computer Science & Engineering. It outlines the project's objectives, methodology, and contributions, focusing on a web-based platform that enhances healthcare management through AI integration. The report includes sections on system analysis, design, implementation, and future scope, emphasizing the importance of privacy and collaboration in healthcare AI systems.
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)
14 views48 pages

Final 3

The document is a mini project report on the 'AI Medical Assistant' developed by Shikhar Singh as part of his Bachelor of Technology in Computer Science & Engineering. It outlines the project's objectives, methodology, and contributions, focusing on a web-based platform that enhances healthcare management through AI integration. The report includes sections on system analysis, design, implementation, and future scope, emphasizing the importance of privacy and collaboration in healthcare AI systems.
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

AI Medical Assistant

A Mini Project Report Submitted


In Partial Fulfilment of the Requirements
for the Degree of

Bachelor of Technology (B. Tech.)


in
Computer Science & Engineering
By

Shikhar Singh
(2304220100163)
Under the Supervision of
Mr. Deepanshu Pandey
(Assistant Professor)
BANSAL INSTITUTE OF ENGINEERING & TECHNOLOGY
LUCKNOW,

Affiliated to
DR. A.P.J. ABDUL KALAM TECHNICAL UNIVERSITY
LUCKNOW, UTTAR PRADESH
DECEMBER, 2025

I
DECLARATION

I, Shikhar Singh (Roll. No.:2304220100163), hereby declare that the Minor Project entitled
" AI Medical Assistant " submitted in partial fulfillment of the requirements for the degree
of Bachelor of Technology in Computer Science & Engineering at the Bansal Institute
of Engineering & Technology, Lucknow, is an original work carried out by me.

I further declare that this project has not been submitted to any other institution or
university for the award of any degree, diploma, or fellowship and that all sources of
information used have been duly acknowledged.

Shikhar Singh
(2304220100163)
B. Tech. (CSE)
BIET, Lucknow
Date_________

II
CERTIFICATE

This is to certify that the report entitled “AI Medical Assistant”, submitted by
Shikhar Singh (Roll. No.: 2304220100163), a student of Bachelor of Technology in
Computer Science & Engineering, in partial fulfillment of the requirements for
the completion of the degree program, is a bonafide record of the research work
carried out under my supervision and guidance.

The work embodied in this thesis has not been submitted to any other University/
Institute for the award of any degree or diploma.

Mr. Deepanshu Pandey Dr. Rohitashwa Pandey


(Assistant Professor) (Head of Department)

CSE Department CSE Department


BIET, Lucknow BIET, Lucknow
Date_______________ Date_______________

III
ACKNOWLEDGEMENT

I would like to express my profound gratitude and sincere appreciation to everyone


who supported and guided me throughout the journey of this project, " AI Medical
Assistant "

First and foremost, I extend my deepest thanks to my project guide, Mr. Deepanshu
Pandey, for his invaluable mentorship, constant encouragement, and insightful
feedback. His expertise and patience were instrumental in navigating challenges and
shaping this project to its successful completion. His unwavering support and
dedication went above and beyond, for which I am truly grateful.

I am also indebted to Dr. Rohitashwa Pandey, Head of the Department of


Computer Science & Engineering, for providing the necessary resources and a
conducive environment for research and development. His leadership and vision are
a constant source of inspiration.

My sincere appreciation goes to the entire faculty and staff of the CSE department
for their direct and indirect contributions to my academic growth.I wish to thank my
colleagues and friends for fostering a collaborative and stress-free working
atmosphere. Their camaraderie, stimulating discussions, and moral support were
crucial throughout this endeavour.

Finally, I would like to acknowledge that while every effort has been made to ensure
the accuracy of the work presented, any errors or omissions are entirely my own.

Shikhar Singh
(2304220100163)
CSE Department
BIET, Lucknow

IV
ABSTRACT

The AI Medical Assistant developed in this project is a comprehensive web-based


platform designed to streamline medical information management and enhance the
healthcare service experience. The system aims to replace traditional, manual healthcare
processes with a modern, automated solution that provides continuous access to medical
resources for both doctors and patients.

The platform integrates two core modules: Admin (Doctor) Module and Patient Module,
each addressing the specific needs of its users.

Through the Admin/Doctor Module, medical professionals can efficiently manage patient
records, upload and update prescriptions, maintain medical histories, monitor health data,
and oversee system configurations. This ensures centralized control, improved accuracy,
and effective supervision of healthcare operations. The system also incorporates secure
login features, structured medical data storage, and intuitive navigation to provide a smooth
workflow for healthcare practitioners.

The Patient Module is designed to offer users a convenient and interactive way to access
their medical information. Patients can log into the system to view prescriptions, check
upcoming appointments, track their medical history, receive health tips, and stay updated
with doctor recommendations. The platform enhances communication by sending timely
notifications and delivering medical updates directly to the patient. By offering 24/7
accessibility and a user-friendly interface, the AI Medical Assistant supports quick
decision-making, improves patient engagement, and promotes better healthcare awareness.

Overall, this project demonstrates how combining artificial intelligence with healthcare
can create an efficient, reliable, and scalable environment for both doctors and patients. It
simplifies healthcare management, reduces manual errors, and ensures a more organized,
accessible, and effective medical ecosystem.

V
TABLE OF CONTENTS
[Link] Object Page No.
1 Front Page I
2 Declaration II
3 Certificate III
4 Acknowledgement IV
5 Abstract V
6 Table of Content VI-VII

VI
TABLE OF CONTENTS

S Object Page No.


No.
1. CHAPTER 1 : INTRODUCTION 1-3
1.1 Problem Statement
1.2 Objectives
1.3 Problem Definition
2. CHAPTER 2 : System Analysis 4-7
2.1 Objective
2.2 System Overview & Components
2.3 Technical Architecture Description
2.4Data Flow Diagram & Processing
3. CHAPTER 3 : TECHNOLOGY STACK USED 8-8
3.1 Software Requirements
3.2 Hardware Requirements
3.3 External Resources

4. CHAPTER 4 : System Design 9 - 11


4.1 Architecture Design
4.2 Design Methodology Applied
5. CHAPTER 5 : Testing & Evaluation 12 - 19
5.1 Privacy Attack Evaluation
5.2 Accuracy & Performance Testing
5.3 Explainability Validation
6. CHAPTER 6 : IMPLEMENTATION 20- 22
6.1 Implementation & Algorithms
6.2 Backend Implementation
6.3 SHAP/LIME Explainability
7 CHAPTER 7 : PROJECT CODING 23 - 36

VII
8 CHAPTER 8 : FUTURE SCOPE 37 - 37

9 CHAPTER 9: CONCLUSION 38 - 38

10 CHAPTER 10: REFERENCES 39 - 39

VIII
LIST OF FIGURES & SCREENSHOTS

S. No. Title Page No.


1. Software Development Life Cycle 16
2. Development Phases 18
3. E–R Diagram 20
4. Zero Level Data Flow Diagram 22
5. One Level Data Flow Diagram 22
6. Top–Down Designing 24
7. Bottom–Up Designing 24

IX
1. Introduction
1.1 Motivation and Problem Statement
Artificial Intelligence (AI) has emerged as a transformative technology in healthcare,
enabling early disease detection, personalized treatment, and improved clinical outcomes.
Modern deep-learning models—when trained on large and diverse medical datasets—can
achieve diagnostic accuracy comparable to or even surpassing human specialists in areas
such as diabetic retinopathy, cardiac disease prediction, and early cancer screening.
However, the major obstacle limiting AI advancement in healthcare is the decentralized and
highly fragmented nature of medical data. Hospitals and research institutions rarely share
patient records due to strict privacy regulations such as HIPAA, GDPR, and similar global
frameworks. These laws are essential for protecting patient confidentiality but severely
restrict cross-institutional data exchange.
As a result, AI models are typically trained on small, siloed datasets, leading to several
drawbacks:
Data Scarcity: Hospitals often lack adequate samples, especially for rare diseases.
Demographic Bias: Limited datasets cause models to perform inconsistently across
population groups.
Model Instability: Narrow training diversity reduces robustness when exposed to new
demographics or imaging variations.
Lower Accuracy: Poor generalization leads to reduced diagnostic performance in real-world
clinical settings.
Thus, there is a strong need for a collaborative yet privacy-preserving AI ecosystem that
allows hospitals to contribute to shared model development without compromising patient
privacy.

1.2 Technical Challenges in Decentralized Healthcare AI


Even when institutions are willing to collaborate, several technical barriers prevent secure,
effective, and scalable AI model training across distributed datasets:
1. Privacy Attack Vectors
Methods like Federated Learning (FL) avoid central data collection but remain vulnerable to
attacks such as:
Gradient inversion
Membership inference
Attackers may reconstruct or infer sensitive patient details from shared model updates.
2. Non-IID Data Issues
Data across hospitals differ due to demographics, regional factors, and equipment variations.
This non-IID distribution often leads to unstable federated training and degraded global
model accuracy.
3. Communication Overhead
Federated Learning requires repeated transfer of large model parameters, resulting in:
High bandwidth usage
Increased latency
Scalability challenges
4. Interpretability Gap
Deep learning models are often “black boxes.”
1
Clinicians require transparent and explainable predictions to trust AI-driven
diagnoses.
5. Regulatory Compliance
Healthcare AI systems must satisfy legal and ethical standards (HIPAA,
GDPR).
They require:
Privacy guarantees
Auditable mechanisms
Secure data-handling workflows

1.3 PEXPO’s Unified Approach


The PEXPO system introduces a unified, privacy-preserving, and interpretable AI
framework designed specifically for collaborative healthcare model training.
It integrates three core technologies:
1. Federated Learning (FL)
Multiple hospitals train a shared global model without sharing patient data.
Each institution trains locally and sends only encrypted model updates.
A central server aggregates updates to improve the global model.
2. Differential Privacy (DP)
Injects statistical noise into model updates.
Ensures that no individual patient record can be reconstructed or inferred.
Protects against privacy attacks such as gradient inversion and membership inference.
3. Explainable AI (XAI)
Uses techniques like SHAP and LIME to provide:
Transparent reasoning behind predictions
Clinician-friendly explanations
Improved reliability and trust in AI decisions
The novelty of PEXPO lies in its integrated architecture, combining FL, DP, and XAI into a
cohesive, secure, and regulation-compliant pipeline suitable for real-world healthcare settings.

1.4 Contributions of This Work


The PEXPO project makes the following key contributions:
Integrated Framework:
A complete architecture combining Federated Learning, Differential Privacy, and
Explainable AI for secure medical model training.
Privacy Evaluation:
Quantitative analysis of privacy preservation methods under realistic attacks such as
membership inference and gradient inversion.
Non-IID Data Handling:
Adaptive aggregation strategies to address uneven data distributions across healthcare
nodes.
Clinical Explainability:
SHAP and LIME-based explanations validated with domain expert feedback to ensure
medical alignment

2
.
Performance Trade-off Analysis:
Evaluation of privacy–accuracy balance under varying DP configurations.

Deployment Blueprint:
A scalable, practical deployment architecture designed for hospital networks, ensuring
security, maintainability, and real-world usability.

Summary
PEXPO introduces a secure, interpretable, and scalable AI framework for collaborative
healthcare intelligence. By integrating Federated Learning, Differential Privacy, and
Explainable AI into a unified pipeline, it overcomes long-standing issues of data privacy,
limited interpretability, and model inconsistency.
This approach enables the creation of ethical, regulation-compliant, and clinically reliable AI
systems that can be deployed across hospitals worldwide without compromising patient
confidentiality.

3
2. SYSTEM ANALYSIS
2.1 Objective
System Analysis is a structured process used to collect facts, study existing operations,
identify problems, and break a system into smaller, manageable components.
It helps in understanding how the system works and what improvements are required to
make it more efficient, reliable, and user-friendly.
This phase clearly defines:
What the system should achieve?
What functionalities it should include?
What operational requirements must be fulfilled?
In simple terms, System Analysis ensures that every component works together
effectively to meet the organization’s objectives.

2.2 System Development Life Cycle (SDLC) Phases


The System Development Life Cycle (SDLC) provides a systematic framework for
planning, developing, testing, and deploying software systems.
It consists of seven well-defined phases, each ensuring quality and reliability.

2.2.1 Preliminary Investigation


This is the first and most essential phase of SDLC.
Its main goal is to:
 Understand the client’s needs
 Identify system objectives
 Determine the scope of the project
 Analyze the problems with the existing system
Before development begins, it is important to understand what the client expects and what
issues the new system must solve.

Feasibility Study
A feasibility study evaluates whether the proposed system can be developed with
available resources, time, and technology.
It identifies potential risks, costs, benefits, and required constraints before moving ahead.
Below are the major types of feasibility:

1. Technical Feasibility
Assesses whether the system can be developed using existing hardware, software, and
human resources.
It answers:
 Can the project be completed using available technology?
 If new technology is required, can it be acquired?

2. Economic Feasibility
Evaluates the financial viability of the project.

4
It checks:
 Are the expected benefits greater than the development cost?
 What financial losses occur if the system is not developed?
It ensures that the system provides value for money.

3. Legal Feasibility
Ensures the system follows all legal and regulatory requirements, such as:
 Software license compliance
 Data protection laws
 Contract obligations
This helps avoid legal disputes or penalties.

4. Operational Feasibility
Examines whether the system will function smoothly in the current environment.
It checks:
 Will the users accept and use the system?
 Will it improve existing workflow and operations?

5. Social & Behavioral Feasibility


Studies user adaptability and comfort level with the new system.
It considers:
 Will users be able to adjust to the new interface?
 Does the system match organizational culture?
It focuses on user satisfaction and long-term acceptance.

Request Approval
After completing the feasibility study, a Request Approval Document is prepared.
This document includes:
 Finalized requirements
 Scope
 Deliverables
 Timelines
Development begins only after formal approval is received.

2.2.2 System Analysis


After approval, System Analysis begins.
This phase studies the existing system to identify:
 Inefficiencies
 Redundancies
 User problems
 Requirements
The main output of this phase is the System Requirement Specification (SRS).
This ensures the proposed system matches organizational goals and user expectations.

2.2.3 System Design


5
System Design converts the gathered requirements into a complete blueprint for the
system.
It includes two types:
1. Logical Design
Focuses on what the system must do.
Includes:
 Data flow
 System processes
 Relationships
2. Physical Design
Defines how the system will work in practice using actual:
 Hardware
 Software
 Network
 Database technologies
Together, they ensure the system is organized, efficient, and scalable.

2.2.4 Coding
In this phase, the design is converted into executable code.
Key points:
 Developers write code using suitable programming languages
 Modular programming is used
 Code is divided into independent units
 Both top-down and bottom-up approaches may be used
This results in clean, reusable, and maintainable code.

2.2.5 Testing
Testing ensures the software is error-free, reliable, and works as intended.
Common testing types include:
 Unit Testing – Tests individual modules
 Integration Testing – Tests combined modules
 System Testing – Tests complete application
 User Acceptance Testing (UAT) – Final testing by users
Testing ensures the system meets all functional and technical requirements.

2.2.6 Implementation
In this phase, the system is installed and made operational.
Implementation strategies include:
 Parallel Conversion: Old and new system run together
 Direct Conversion: Immediate replacement of the old system
 Pilot Conversion: Implemented in one area first
 Phased Conversion: Implemented module-by-module
Successful implementation ensures a smooth transition.

2
6
.2.7 Maintenance
After deployment, maintenance ensures that the system continues to operate efficiently.
It includes:
 Fixing errors
 Improving performance
 Updating the system as per new requirements
Maintenance is usually free during the warranty period, after which it becomes a paid
service.
2.1.1 TECHNICAL FEASIBILITY (Medical Assistant System)
 feasibility evaluates whether the AI–Based Medical Assistant System can be developed with
the
 available technology, tools, and skills.
 It includes the following questions:
• Can the project be built with the current equipment, software, and manpower?
 Yes. The project uses easily accessible technologies such as:
 HTML, CSS, JavaScript (Frontend)
 [Link] / Technical Python (Backend)
 AI APIs (OpenAI / NLP Models)
 Browser Speech Synthesis
 OCR Engine (Tesseract)
 All these technologies run on a normal laptop without specialized hardware.
• If new technology is required, can it be developed or implemented?
 Yes. The AI-based chatbot and OCR modules use open-source libraries and APIs, making it
easy to extend the system with additional medical features.
No expensive hardware or proprietary software is required.

2.1.2 ECONOMIC FEASIBILITY
 Economic feasibility studies whether the project is financially viable.
 This includes the questions:
• Are the benefits sufficient to justify the cost?
 Yes. The project is cost-effective because:
 Uses free/open-source tools
 Requires no server cost (can run locally)
 Reduces manual effort in medical assistance
 Improves accuracy & reduces time
• Are the costs of not developing the system high?
 Yes. Without this system:
 Users struggle to access basic medical information
 Medical stores waste time answering repeated queries
 Human errors occur frequently
 Expiry/loss in pharmacies increases
 Thus, implementation is economically beneficial.

2.1.3 LEGAL FEASIBILITY


7
 Legal feasibility checks whether the project violates any laws.
 The following legal points are considered:
 ✔ Contract Signing
 No contract issues exist because the project is academic.
 ✔ Software License Agreement
 All tools used (OCR, APIs, JavaScript libraries) are open-source or free for educational use.
 ✔ Cyber Law Considerations
 The project:
 Does NOT store sensitive patient data
 Does NOT access private medical records
 Follows safe AI rules and does not prescribe controlled medicines
 ✔ Manpower Contract Issues
 Not applicable since this is a student project.
 The system is fully legally feasible.

2.1.4 OPERATIONAL FEASIBILITY
 This feasibility checks whether the system will operate smoothly in real environments.
• Will the system be useful if developed?
 Yes. It will help users by:
 Answering medical queries
 Providing symptom guidance
 Giving OTC medicine suggestions
 Helping medical shop owners with expiry alerts
• Will employees or users resist the system?
 Minimal resistance is expected because:
 The system is simple to use
 It improves efficiency
 It reduces manual work
 It does not replace medical professionals

2.1.5 SOCIAL & BEHAVIORAL FEASIBILITY
 This feasibility checks whether users will accept the system socially.
 ✔ Will users adapt to this new change?
 Yes. AI-based medical help is becoming very common and well-accepted.
 ✔ Does the system provide a friendly user environment?
 Yes.
 Clean UI
 Simple chatbot interaction
 Easy voice input/output
 Fast response
All make it suitable for all age groups.

REQUEST APPROVAL

8
 Request approval is the final part of preliminary investigation.
Expiry alert system It acts as an agreement between the client and developer.
 In this project, the requirements include:
 AI chatbot
 Medicine database
 Symptom checker
 OCR prescription reader
 Speech input/output

 Both parties must agree on these requirements before development.



 System analysis is the phase after approval.
Here, the full structure of the Medical Assistant System is studied and converted into
functional modules.
 It includes:
 Data flow
 User requirements
 Functional and non-functional requirements
 Input-output descriptions
 This is a crucial step for the system's success.

2.1.7 SYSTEM DESIGN
 System design converts the analysis into a technical blueprint.
 It includes:
• Logical System Design
 AI interaction flow
 Chatbot logic
 Symptom mapping
 Data entities
 Processes & interactions
• Physical System Design
 Database structure
 API architecture
 User interface layout
 Module interactions

2.1.8 CODING
 Coding is the actual implementation of the design.
 Uses HTML, CSS, JavaScript
 Backend with [Link]/Python
 AI APIs for responses
 Speech Synthesis API
 Only 20% of the overall time is spent on coding, but modular coding ensures easier testing.

2.1.9 TESTING
 Testing involves checking the system for errors.
9
 It includes:
 Unit testing
 System testing
 Integration testing
 Black-box testing
 White-box testing
 Testing ensures:
 Correct responses
 Safe medical suggestions
 Proper OCR extraction
 Smooth UI functioning

2.1.10 IMPLEMENTATION
 Implementation includes deploying the system for user use.
 Conversion approaches:
 Parallel (old + new system together)
 Direct (shift to new system instantly)
 Pilot (test version first)
 Phase-In (feature-by-feature rollout)
 For this project, Pilot approach is suitable.

2.1.11 MAINTENANCE
 Maintenance includes:
 Fixing bugs
 Updating AI model
 Adding new medicines
 Improving symptom logic
 UI enhancements
 The system requires continuous improvement as medical knowledge evolves.

2.2 PROCESS DESCRIPTION
 Gantt charts are used to schedule project phases:
 Phase  Month
 Requirement Analysis  January
 Design  January–February
 Development  February–March
 Testing  March
 Deployment  April
 Progress is measured by completing milestones.

2.3 PROJECT MODEL USED – ITERATIVE ENHANCEMENT
MODEL
 The project follows the Iterative Enhancement Model, similar to waterfall but more flexible.
 Key Features:
10
 Each cycle adds new features
 Users can test early versions
 Requirements can be updated
 Development is modular and flexible
 Model Phases:
 Inception – Define scope & risks
 Elaboration – Build core architecture
 Construction – Implement features gradually
1. Transition – Deploy system for use
 This model is best for AI-based systems because improvements are continuous.

2.1. ER–DIAGRAM
o Introduction:
o In software engineering, an Entity–Relationship Model (ERM) is a conceptual and abstract
o representation of the data elements within a system. It is used to establish the logical structure
o of a database through entities, their attributes, and the relationships that exist between them.
o The AI–Based Medical Assistant System also requires proper organization of data such as
users,
o medical queries, symptoms, medicines, and AI-generated responses.
To represent this data clearly, an ER Diagram is used.
o An ER Diagram is extremely helpful because:
 It identifies data objects (entities)
 It defines relationships among those objects
 It helps in converting conceptual design into a relational database
 It supports normalization and table creation
o The entity–relationship model uses the following three main components:
o Entities represent real-world objects or concepts within the medical assistant system, such as:
 User
 Medical Query
 Medicine Database
 AI Response
 Symptoms
o These entities hold data that the system needs to store permanently.
 Relationships
o Relationships show how entities interact with each other, such as:
 A User sends a Medical Query
 The AI Engine processes symptoms and generates an AI Response
 The Medicine Database stores information about medicines suggested to users
o These relationships help in designing the database structure.
 Attributes
o Attributes are the properties or details of each entity. For example:
 User → Name, Age, Gender
 Symptoms → Symptom Name, Severity

11
 Medicine → Name, Type, Dosage
 AI Response → Output, Recommendation, Precaution
o These attributes help define table columns in the database.
o Medical_Query (Query_ID, Symptoms, Time
2.2. DATA FLOW DIAGRAM (DFD)
 Introduction:
o A Data Flow Diagram (DFD) is a pictorial representation that shows how data flows within a
system. It visually represents processes, data movement, data storage, and interactions
between system
o components.
o For the AI–Based Medical Assistant System, the DFD shows how:
 User inputs symptoms
 Data flows to AI processing
 The AI generates responses
 The system accesses the medicine database
 The final result is displayed to the user
o DFDs are widely used in structured system analysis because they:
 Are simple and easy to understand
 Provide a clear high-level overview of the system
 Help identify required processes and data storage
 Represent system boundaries and interactions
o A DFD includes:
o ✔ External Entities
o Represent sources or destinations of data, such as:
 User
o ✔ Processes
o Represent operations performed on data, such as:
 Analyze Symptoms
 Generate AI Response
o ✔ Data Stores
o Internal data repositories like:
 Medicine Database
 Query History
o ✔ Data Flows

12
Step-by-Step Flow Description:
1. User Request
A user performs an action (like visiting a URL or submitting a form).
The browser sends an HTTP request to the Django server.
2. URL Dispatcher ([Link])
Django checks the URL patterns defined in [Link].
It finds the correct view function (or class-based view) that matches the
requested URL.
3. View Function ([Link])
The matched view receives the request.
Here, the business logic is executed (validation, calculations, decisions, etc.).
4. View → Model
If data is required, the view interacts with the Model.
This could be for retrieving, creating, updating, or deleting data.

5. Model → Database
The Model translates Python operations into SQL queries behind the scenes.
These queries are executed on the connected database
(SQLite/MySQL/PostgreSQL).

6. Database → Model
The database sends back the result of the query.
13
This could be objects, values, lists, or error messages.

14
ER–DIAGRAM

15
3. SOFTWARE & HARDWARE REQUIREMENT SPECIFICATION
(SRS)
A Software Requirement Specification (SRS) is a complete and structured description of all the
functionalities, behaviors, and constraints of the system to be developed. It includes:
 Functional Requirements (use cases, system behavior)
 Non-Functional Requirements (performance, usability, security, reliability)
The SRS provides a clear understanding of the system for both developers and users. It is prepared after
detailed discussions with the project team and the stakeholders.

3.1 Server-Side Hardware Requirements


• Dual-Core or higher processor
• Minimum 4 GB RAM
• 40 GB or higher storage
• Network Interface Card
• Stable Internet Connection
(Note: Revised to modern realistic specs suitable for web projects.)

3.2 Server-Side Software Requirements


• Windows / Linux operating system
• Notepad++ / VS Code
• Modern Web Browser (Chrome, Edge, Firefox)
• In-built local web server / Live Server

3.3 Client-Side Hardware Requirements


• Dual-core processor
• Minimum 2 GB RAM
• 20 GB HDD / SSD
• 100 Mbps LAN / Wi-Fi
• Any modern web browser

3.4 Software Resources Used in the Project


• Front-End: HTML, CSS, Bootstrap
• Back-End: JavaScript
• Web Server: In-built browser-based runtime
• Technologies Used: SpeechSynthesis, SpeechUtterance APIs
• IDE: Notepad++

3.5 Support and Maintenance


The system includes one-year free support for fixing bugs in both front-end and back-end modules.
During the warranty period, developers will:
• Resolve system errors
• Improve minor features
• Ensure smooth functionality

16
4. SYSTEM DESIGN APPROACH
4.1 Top-Down Design
Top-down design begins with the overall system and breaks it into smaller, more detailed components.
Each level increases detail until no further refinement is required.
4.2 Bottom-Up Design
Bottom-up design starts by developing the smallest, most basic components first.
These components are combined step-by-step to form higher-level modules.
4.3 Mixed Approach (Followed in This Project)
This project uses a mixed approach:
• Web pages designed using Top-Down method
• Middle-layer logic developed using Bottom-Up method
This approach reduces complexity and improves clarity during development.

17
5. TESTING

Testing ensures the system performs correctly, reliably, and according to the requirements. It is the final
opportunity to detect errors before deployment.

5.1 Types of Testing


5.1.1 Black-Box (Functional) Testing
Testing based on system functionality without seeing the internal code.
Used to detect:
• Missing functions
• Interface issues
• Errors in data access
• Performance problems
• Initialization and termination errors
5.1.2 White-Box (Structural) Testing
Testing internal logic, code structure, and execution paths.
Includes:
• Condition testing
• Loop testing
• Path coverage
• Statement coverage
5.1.3 Unit Testing
Each module is tested individually to verify correctness.
Done during the coding phase using white-box techniques.
5.2 Incremental Integration Testing
Modules are tested step-by-step as new features are added.
5.2.1 Integration Testing
Testing combined modules to check communication and data flow between them.

18
19
[Link]
Input-output Forms(SCREENSHOTS AND CODING)

6.1 Project Screenshot

6.1.1 Home page

6.1.2 User input page

20
[Link] CODING
"""Streamlit Dashboard for Federated Learning Disease Prediction."""

import sys
from pathlib import Path

# Add project root to Python path


project_root = Path(__file__).[Link]
[Link](0, str(project_root))

import streamlit as st
import pandas as pd
import numpy as np
import torch
import yaml
import [Link] as px
import plotly.graph_objects as go
from [Link] import make_subplots

from [Link] import DiseasePredictor


from [Link] import DataPreprocessor
from explainability.shap_explainer import SHAPExplainer
from explainability.lime_explainer import LIMEExplainer
from [Link] import calculate_metrics

# Page configuration
st.set_page_config(
page_title="FL Disease Prediction Dashboard",
page_icon=" ",
layout="wide",
initial_sidebar_state="expanded"
)

# Custom CSS

21
[Link]("""
<style>
.main-header {
font-size: 2.5rem;
font-weight: bold;
color: #1f77b4;
text-align: center;
margin-bottom: 2rem;
}
.metric-card {
background-color: #f0f2f6;
padding: 1rem;
border-radius: 0.5rem;
border-left: 4px solid #1f77b4;
}
.stAlert {
margin-top: 1rem;
}
</style>
""", unsafe_allow_html=True)

@st.cache_resource
def load_config():
"""Load configuration file."""
config_path = Path("configs/fl_config.yaml")
with open(config_path, 'r') as f:
return yaml.safe_load(f)

@st.cache_resource
def load_model_and_data(config):
"""Load trained model and test data."""
try:
# Load preprocessor or create feature names
preprocessor_path = Path(config['paths']['processed_data_dir']) / "[Link]"
try:
import pickle
with open(preprocessor_path, 'rb') as f:

22
preprocessor_info = [Link](f)
feature_names = preprocessor_info.get('feature_names', [f'feature_{i}' for i in range(13)])
except:
# Default heart disease feature names
feature_names = [
'age', 'sex', 'cp', 'trestbps', 'chol', 'fbs', 'restecg',
'thalach', 'exang', 'oldpeak', 'slope', 'ca', 'thal'
]

# Load test data


test_path = Path(config['paths']['processed_data_dir']) / "test_data.pt"
test_data = [Link](test_path, weights_only=False)
X_test = test_data['X']
y_test = test_data['y']

# Load model
model_path = Path(config['paths']['models_dir']) / "best_model.pt"
checkpoint = [Link](model_path, weights_only=False)

# Create model
input_size = X_test.shape[1]
model = DiseasePredictor(
input_size=input_size,
hidden_layers=config['model']['hidden_layers'],
output_size=config['model']['output_size'],
dropout=config['model']['dropout'],
batch_norm=config['model']['batch_norm'],
activation=config['model']['activation']
)

model.load_state_dict(checkpoint['model_state_dict'])
[Link]()

return model, X_test, y_test, feature_names


except Exception as e:
[Link](f"Error loading model: {e}")
return None, None, None, None

23
def main():
"""Main dashboard function."""

# Header
[Link]('<h1 class="main-header"> Privacy-Preserving Federated Learning
Dashboard</h1>', unsafe_allow_html=True)
[Link]("### Early Disease Prediction with Explainable AI")

# Load configuration
config = load_config()

# Sidebar
[Link]("Navigation")
page = [Link](
"Select Page",
["Overview", "Model Performance", "Explainability", "Privacy Analysis", "Patient
Prediction"]
)

# Load model and data


model, X_test, y_test, feature_names = load_model_and_data(config)

if model is None:
[Link](" Model not found. Please train the model first.")
[Link]("Run the following commands to train the model:")
[Link]("""
# 1. Download and partition data
python preprocessing/data_loader.py --download
python preprocessing/[Link] --num-clients 3

# 2. Start FL server (in one terminal)


python federated/[Link] --rounds 50

# 3. Start FL clients (in separate terminals)


python federated/[Link] --client-id 0
python federated/[Link] --client-id 1
python federated/[Link] --client-id 2
""")
return

24
# Route to pages
if page == "Overview":
show_overview(config, model, X_test, y_test, feature_names)
elif page == "Model Performance":
show_model_performance(model, X_test, y_test)
elif page == "Explainability":
show_explainability(model, X_test, y_test, feature_names, config)
elif page == "Privacy Analysis":
show_privacy_analysis(config)
elif page == "Patient Prediction":
show_patient_prediction(model, feature_names, config)

def show_overview(config, model, X_test, y_test, feature_names):


"""Show overview page."""
[Link](" System Overview")

# Key metrics
col1, col2, col3, col4 = [Link](4)

with col1:
[Link]("FL Rounds", config['federated']['num_rounds'])
with col2:
[Link]("Clients", config['federated']['min_clients'])
with col3:
[Link]("Features", len(feature_names))
with col4:
[Link]("Test Samples", len(X_test))

[Link]("---")

# Model architecture
col1, col2 = [Link](2)

with col1:
[Link](" Model Architecture")
arch_data = {
"Layer": ["Input", "Hidden 1", "Hidden 2", "Hidden 3", "Output"],

25
"Size": [
len(feature_names),
config['model']['hidden_layers'][0],
config['model']['hidden_layers'][1],
config['model']['hidden_layers'][2],
config['model']['output_size']
]
}
[Link]([Link](arch_data))

with col2:
[Link](" Privacy Configuration")
privacy_data = {
"Parameter": ["Epsilon (ε)", "Delta (δ)", "Max Grad Norm", "DP Enabled"],
"Value": [
config['privacy']['epsilon'],
f"{config['privacy']['delta']:.0e}",
config['privacy']['max_grad_norm'],
" " if config['privacy']['enable_dp'] else " "
]
}
[Link]([Link](privacy_data))

[Link]("---")

# Quick performance summary


[Link](" Quick Performance Summary")

with torch.no_grad():
outputs = model(X_test)
probs = [Link](outputs).numpy().flatten()
preds = (probs >= 0.5).astype(int)
y_true = y_test.numpy().flatten()

metrics = calculate_metrics(y_true, preds, probs)

col1, col2, col3, col4 = [Link](4)

with col1:

26
[Link]("Accuracy", f"{metrics['accuracy']:.3f}")
with col2:
[Link]("AUROC", f"{metrics['auroc']:.3f}")
with col3:
[Link]("F1-Score", f"{metrics['f1_score']:.3f}")
with col4:
[Link]("Precision", f"{metrics['precision']:.3f}")

def show_model_performance(model, X_test, y_test):


"""Show model performance page."""
[Link](" Model Performance Analysis")

# Get predictions
with torch.no_grad():
outputs = model(X_test)
probs = [Link](outputs).numpy().flatten()
preds = (probs >= 0.5).astype(int)
y_true = y_test.numpy().flatten()

# Calculate metrics
metrics = calculate_metrics(y_true, preds, probs)

# Display metrics
[Link]("Performance Metrics")

col1, col2, col3 = [Link](3)

with col1:
[Link]("Accuracy", f"{metrics['accuracy']:.4f}")
[Link]("Precision", f"{metrics['precision']:.4f}")
[Link]("Recall", f"{metrics['recall']:.4f}")

with col2:
[Link]("F1-Score", f"{metrics['f1_score']:.4f}")
[Link]("Specificity", f"{metrics['specificity']:.4f}")
[Link]("Sensitivity", f"{metrics['sensitivity']:.4f}")

with col3:

27
[Link]("AUROC", f"{metrics['auroc']:.4f}")
[Link]("AUPRC", f"{metrics['auprc']:.4f}")

[Link]("---")

# Confusion Matrix
col1, col2 = [Link](2)

with col1:
[Link]("Confusion Matrix")
from [Link] import confusion_matrix
cm = confusion_matrix(y_true, preds)

fig = [Link](data=[Link](
z=cm,
x=['No Disease', 'Disease'],
y=['No Disease', 'Disease'],
colorscale='Blues',
text=cm,
texttemplate='%{text}',
textfont={"size": 20}
))
fig.update_layout(
title="Confusion Matrix",
xaxis_title="Predicted",
yaxis_title="Actual",
height=400
)
st.plotly_chart(fig, use_container_width=True)

with col2:
[Link]("Prediction Distribution")

fig = [Link]()
fig.add_trace([Link](
x=probs[y_true == 0],
name='True Negative',
opacity=0.7,
marker_color='blue'

28
))
fig.add_trace([Link](
x=probs[y_true == 1],
name='True Positive',
opacity=0.7,
marker_color='red'
))

fig.update_layout(
title="Prediction Probability Distribution",
xaxis_title="Predicted Probability",
yaxis_title="Count",
barmode='overlay',
height=400
)
st.plotly_chart(fig, use_container_width=True)

# ROC Curve
[Link]("ROC Curve")
from [Link] import roc_curve

fpr, tpr, _ = roc_curve(y_true, probs)

fig = [Link]()
fig.add_trace([Link](
x=fpr, y=tpr,
mode='lines',
name=f'ROC Curve (AUC = {metrics["auroc"]:.3f})',
line=dict(color='blue', width=2)
))
fig.add_trace([Link](
x=[0, 1], y=[0, 1],
mode='lines',
name='Random Classifier',
line=dict(color='gray', dash='dash')
))

fig.update_layout(
title="Receiver Operating Characteristic (ROC) Curve",

29
xaxis_title="False Positive Rate",
yaxis_title="True Positive Rate",
height=500
)
st.plotly_chart(fig, use_container_width=True)

def show_explainability(model, X_test, y_test, feature_names, config):


"""Show explainability page."""
[Link](" Model Explainability")

# Load or generate explanations


explanations_dir = Path(config['paths']['explanations_dir'])

# Feature importance
[Link]("Feature Importance")

try:
# Try to load pre-computed importance
importance_path = explanations_dir / "feature_importance.csv"
if importance_path.exists():
importance_df = pd.read_csv(importance_path)

# Plot
fig = [Link](
importance_df.head(15),
x='importance',
y='feature',
orientation='h',
title='Top 15 Most Important Features (SHAP)',
labels={'importance': 'SHAP Importance', 'feature': 'Feature'}
)
fig.update_layout(yaxis={'categoryorder': 'total ascending'}, height=500)
st.plotly_chart(fig, use_container_width=True)
else:
[Link]("Feature importance not computed yet. Run SHAP explainer first.")
if [Link]("Generate SHAP Explanations"):
with [Link]("Generating SHAP explanations..."):
# Generate explanations

30
background_data = X_test[:100].numpy()
explainer = SHAPExplainer(model, background_data, feature_names)
importance_df = explainer.get_feature_importance(X_test[:200].numpy())

# Save
importance_path.[Link](parents=True, exist_ok=True)
importance_df.to_csv(importance_path, index=False)

[Link]("Explanations generated!")
st.experimental_rerun()

except Exception as e:
[Link](f"Error loading explanations: {e}")

[Link]("---")

# Individual instance explanation


[Link]("Individual Instance Explanation")

instance_idx = [Link]("Select Instance", 0, len(X_test) - 1, 0)

if [Link]("Explain Instance"):
with [Link]("Generating explanation..."):
# Get instance
x = X_test[instance_idx:instance_idx+1].numpy()

# Get prediction
with torch.no_grad():
output = model([Link](x))
prob = [Link](output).item()

# Display prediction
col1, col2 = [Link](2)
with col1:
[Link]("Predicted Probability", f"{prob:.4f}")
with col2:
pred_class = "Disease" if prob >= 0.5 else "No Disease"
[Link]("Predicted Class", pred_class)

31
# Feature values
[Link]("Feature Values")
feature_df = [Link]({
'Feature': feature_names,
'Value': [Link]()
})
[Link](feature_df, height=300)

def show_privacy_analysis(config):
"""Show privacy analysis page."""
[Link](" Privacy Analysis")

# Privacy budget
[Link]("Privacy Budget")

epsilon = config['privacy']['epsilon']
delta = config['privacy']['delta']
num_rounds = config['federated']['num_rounds']

col1, col2, col3 = [Link](3)

with col1:
[Link]("Total ε (Epsilon)", f"{epsilon:.2f}")
with col2:
[Link]("δ (Delta)", f"{delta:.0e}")
with col3:
[Link]("ε per Round", f"{epsilon/num_rounds:.4f}")

# Privacy budget consumption


[Link]("Privacy Budget Consumption")

rounds = list(range(1, num_rounds + 1))


epsilon_spent = [epsilon * r / num_rounds for r in rounds]

fig = [Link]()
fig.add_trace([Link](
x=rounds,
y=epsilon_spent,

32
mode='lines+markers',
name='ε Spent',
line=dict(color='red', width=2)
))
fig.add_hline(y=epsilon, line_dash="dash", line_color="green",
annotation_text="Total Budget")

fig.update_layout(
title="Privacy Budget Consumption Over Rounds",
xaxis_title="Federated Learning Round",
yaxis_title="Cumulative ε",
height=400
)
st.plotly_chart(fig, use_container_width=True)

# Privacy parameters
[Link]("Privacy Parameters")

privacy_params = {
"Parameter": [
"Differential Privacy",
"Max Gradient Norm",
"Noise Multiplier",
"Secure Aggregation",
"Accounting Method"
],
"Value": [
" Enabled" if config['privacy']['enable_dp'] else " Disabled",
config['privacy']['max_grad_norm'],
config['privacy'].get('noise_multiplier', 'Auto'),
" Enabled" if config['privacy']['enable_secure_aggregation'] else " Disabled",
config['privacy']['accounting_method'].upper()
]
}
[Link]([Link](privacy_params))

def show_patient_prediction(model, feature_names, config):


"""Show patient prediction page."""

33
[Link](" Patient Risk Prediction")

[Link]("Enter patient information to predict disease risk:")

# Create input form


with [Link]("patient_form"):
[Link]("Patient Information")

# Create inputs for each feature (simplified)


inputs = {}

# Use columns for better layout


col1, col2 = [Link](2)

for i, feature in enumerate(feature_names):


if i % 2 == 0:
with col1:
inputs[feature] = st.number_input(
[Link]('_', ' ').title(),
value=0.0,
step=0.1
)
else:
with col2:
inputs[feature] = st.number_input(
[Link]('_', ' ').title(),
value=0.0,
step=0.1
)

submitted = st.form_submit_button("Predict Risk")

if submitted:
# Create input tensor
x = [Link]([[inputs[f] for f in feature_names]])

# Get prediction
with torch.no_grad():
output = model(x)

34
prob = [Link](output).item()

# Display result
[Link]("---")
[Link]("Prediction Result")

col1, col2, col3 = [Link](3)

with col1:
[Link]("Disease Risk", f"{prob*100:.1f}%")

with col2:
risk_level = "High" if prob >= 0.7 else "Medium" if prob >= 0.4 else "Low"
[Link]("Risk Level", risk_level)

with col3:
pred_class = "Disease" if prob >= 0.5 else "No Disease"
[Link]("Prediction", pred_class)

# Risk gauge
fig = [Link]([Link](
mode="gauge+number",
value=prob * 100,
title={'text': "Disease Risk (%)"},
gauge={
'axis': {'range': [None, 100]},
'bar': {'color': "darkblue"},
'steps': [
{'range': [0, 40], 'color': "lightgreen"},
{'range': [40, 70], 'color': "yellow"},
{'range': [70, 100], 'color': "red"}
],
'threshold': {
'line': {'color': "red", 'width': 4},
'thickness': 0.75,
'value': 50
}
}
))

35
fig.update_layout(height=300)
st.plotly_chart(fig, use_container_width=True)

if __name__ == "__main__":
main()

36
8 . FUTURE SCOPE

Following modifications or upgrades can be done in the system:


1. Integration with multiple hospitals or clinics
More than one healthcare institution can be connected through this software to provide users with
verified medical information and seamless access.
2. Integration of advanced medical web services
Web services can be used to fetch real-time medical updates
such as drug availability, disease alerts, and doctor consultation schedules.
3. Online health monitoring for users
Clients can check their symptom evaluation history, AI-generated recommendations,
and health improvement status online.
4. Doctor–Patient Teleconsultation
The system can be extended to allow live chat or video consultations with certified doctors.
5. IoT-based health tracking
Wearable devices can be connected to monitor heart rate, oxygen level, and
other vitals in real time.
6. Multilingual medical support
The AI assistant can be expanded to support regional languages for wider
accessibility in India.
7. Home-delivery medicine module
Users could order medicines directly from the connected pharmacy stores.
8. Emergency alert system
The system may generate urgent alerts in case of severe
symptoms and guide users to the nearest hospital.

37
9 . CONCLUSION

The AI–Based Medical Assistant System has been successfully developed as a web-based application
designed to provide users with quick and convenient access to basic medical information, symptom guidance,
and medicine suggestions. By integrating Artificial Intelligence, Natural Language Processing, OCR, and
modern web technologies, the system delivers a smooth, user-friendly, and efficient medical support
experience.

This application serves as a valuable assistant for general users, medical store operators, and healthcare
institutions by reducing reliance on manual processes, minimizing human error, and improving accessibility
to essential medical guidance. Its modular structure ensures high scalability and flexibility, allowing
additional functionalities to be incorporated as needed.

Overall, the AI–Based Medical Assistant System is not merely a mini project—it represents a practical and
impactful solution with the potential to evolve into a full-scale healthcare support platform. With further
integration of advanced medical knowledge and intelligent features, the system can become even more
powerful, reliable, and beneficial for real-world healthcare applications.

38
10. REFERENCES

[1] H. B. McMahan, E. Moore, D. Ramage, S. Hampson, and B. A. y Arcas, “Communication-


efficient learning of deep networks from decentralized data,” Proceedings of the 20th International
Conference on Artificial Intelligence and Statistics (AISTATS), 2017.

[2] K. Bonawitz et al., “Practical secure aggregation for privacy-preserving machine learning,”
Proceedings ACM Conference on Computer and Communications Security (CCS), 2017.

[3] M. Abadi et al., “Deep learning with differential privacy,” Proceedings of the ACM Conference
on Computer and Communications Security (CCS), 2016.

[4] S. M. Lundberg and S.-I. Lee, “A unified approach to interpreting model predictions,” Advances
in Neural Information Processing Systems (NeurIPS), 2017.

[5] M. T. Ribeiro, S. Singh, and C. Guestrin, “Why should I trust you?: Explaining the predictions
of any classifier,” Proceedings of the ACM SIGKDD International Conference on Knowledge
Discovery and Data Mining (KDD), 2016.

[6] N. Rieke et al., “The future of digital health with federated learning,” NPJ Digital Medicine,
2020.

[7] J. Xu, Z. Geng, and Q. Pan, “Federated learning in healthcare: A survey,” IEEE/ACM
Transactions on Computational Biology and Bioinformatics, 2021.

39

You might also like