Final 3
Final 3
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.
III
ACKNOWLEDGEMENT
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.
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 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
VII
8 CHAPTER 8 : FUTURE SCOPE 37 - 37
9 CHAPTER 9: CONCLUSION 38 - 38
VIII
LIST OF FIGURES & SCREENSHOTS
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.
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.
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?
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.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.
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
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.
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.
18
19
[Link]
Input-output Forms(SCREENSHOTS AND CODING)
20
[Link] CODING
"""Streamlit Dashboard for Federated Learning Disease Prediction."""
import sys
from pathlib import Path
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
# 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 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]()
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"]
)
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
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)
# 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]("---")
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()
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}")
# 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")
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
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)
# 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]("---")
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']
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}")
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))
33
[Link](" Patient Risk Prediction")
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")
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
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
[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