0% found this document useful (0 votes)
243 views143 pages

Health Predict

The document describes a proposed system for online health disease prediction. It would allow users to input symptoms and get predictions of potential illnesses. The system would use machine learning techniques to analyze symptoms and medical records to make accurate predictions. It would also suggest nearby doctors. This could help users get medical guidance anytime without visiting a doctor in person.

Uploaded by

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

Health Predict

The document describes a proposed system for online health disease prediction. It would allow users to input symptoms and get predictions of potential illnesses. The system would use machine learning techniques to analyze symptoms and medical records to make accurate predictions. It would also suggest nearby doctors. This could help users get medical guidance anytime without visiting a doctor in person.

Uploaded by

Abhinav Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 143

ABSTRACT

It might have happened so many times that you or someone yours need doctors help immediately, but
they are not available due to some reason. The Health Prediction system is an end user support and
online consultation project. Here we propose a system that allows users to get instant guidance on
their health issues through an intelligent health care system online. The system is fed with various
symptoms and the disease/illness associated with those systems. The system allows user to share their
symptoms and issues. It then processes user’s symptoms to check for various illnesses that could be
associated with it. Here we use some intelligent data mining techniques to guess the most accurate
illness that could be associated with patient’s symptoms. In doctor module when doctor login to the
system doctor can view his patient details and the report of that patient. Doctor can view details about
the patient search what patient searched for according to their prediction. Doctor can view his personal
details. Admin can add new disease details by specifying the type and symptoms of the disease into
the database. Based on the name of the disease and symptom the data mining algorithm works.
Admin can view various disease and symptoms stored in database. This system will provide proper
guidance when the user specifies the symptoms of his illness.

1
CHAPTER 1
INTRODUCTION

2
INTRODUCTION
Prediction of health disease may seem tricky, but this is part of user service system (application support direct
contact with user). To predict heart disease according to input parameter values provided by user and
dataset stored in database. The objective of this project entitled “Smart health disease prediction using
machine learning” is to provide a user friendly and easily understandable GUI to users to easily get instant
guidance on their health issues through an intelligent health care system online. The main objective of the
System is to predict disease according to symptoms and also suggest list of nearby doctors.

 User can search for doctor’s help at any point of time.


 User can talk about their illness and get instant diagnosis.
 Informs the user about the type of disease or disorder it feels.
 Doctors get more clients online.

There is always a need of a system that will provide the disease information according to symptoms shared by
user. This system will help the user to find good doctors and medicines.

3
SYSTEM ANALYSIS

4
1.SYSTEM ANALYSIS
System analysis is a process of gathering and interpreting facts, diagnosing problems and the
information to recommend improvements on the system. It is a problem solving activity that
requires intensive communication between the system users and system developers. System
analysis or study is an important phase of any system development process. The system is
studied to the minute’s detail and analyzed. The system analyst plays the role of the interrogator
and dwells deep into the working of the present system. The system is viewed as a whole and the
input to the system are identified. The outputs from the organizations are traced to the various
processes. System analysis is concerned with becoming aware of the problem, identifying the
relevant and decisional variables, analyzing and synthesizing the various factors and determining
an optimal or at least a satisfactory solution or program of action.

A detailed study of the process must be made by various techniques like interviews,
questionnaires etc. The data collected by these sources must be scrutinized to arrive to a
conclusion. The conclusion is an understanding of how the system functions. This system is
called the existing system. Now the existing system is subjected to close study and problem areas
are identified. The designer now functions as a problem solver and tries to sort out the
difficulties that the enterprise faces. The solutions are given as proposals. The proposal is then
weighed with the existing system analytically and the best one is selected. The proposal is
presented to the user for an endorsement by the user. The proposal is reviewed on user request
and suitable changes are made. This is loop that ends as soon as the user is satisfied with
proposal.

Preliminary study is the process of gathering and interpreting facts, using the information for
further studies on the system. Preliminary study is problem solving activity that requires
intensive communication between the system users and system developers. It does various
feasibility studies. In these studies, a rough figure of the system activities can be obtained, from
which the decision about the strategies to be followed for effective system study and analysis can
be taken.

5
1.1 EXISTING SYSTEM

The existing manual process of maintaining a Disesase record, maintain Patients scheduling info, day
to day activities and billing is tough and hence a system or application which can complete these tasks
in an easy to use is what we can achieve by this application.
 Lack of products and time wastage.
 Misuse, mismanagement and corruption in government and non- government bodies.

DRAWBACKS OF EXISTING SYSTEM

 It is a time consuming process


 Paper work results in need of lot of space to keep the data.
 Lack of security
 Chances of human errors
 Huge convenience fees
 Total features are not accessible

1.2 PROPOSED SYSTEM

The project has a wide scope, as it is not intended to a particular organization. This project is
going to develop generic software, which can be applied by any healthcare organization. More
over it provides facility to its users. Also the software is going to provide a huge amount of
summary data.

To beat the downside of existing framework we have created smart health disease prediction System.
We have built up a specialist framework called Smart Health Prediction framework, which is utilized for
improving the task of specialists. A framework checks a patient at initial level and proposes the possible
diseases. It begins with getting some information about manifestations to the patient, in the event that
the framework can distinguish the fitting sickness, at that point it proposes a specialist accessible to the
patient in the closest conceivable territory. On the off chance that the framework isn't sufficiently sure, it
asks few questions to the patients, still on the off chance that the framework isn't sure; at that point it
6
will show a few tests to the patient. In light of accessible total data, the framework will demonstrate the
result. Here we utilize some intelligent methods to figure the most precise disorder that could be
associated with patient's appearances and dependent on the database of a couple of patients restorative
record, calculation (Naïve Bayes) is connected for mapping the side effects with conceivable
diseases.This framework improves undertaking of the specialists as well as helps the patients by giving
vital help at a soonest organize conceivable.

 Patient Login: - Patient Login to the system using his ID and Password.
 Patient Registration: -If Patient is a new user he will enter his personal details and he will user Id
and password through which he can login to the system.
 My Details: - Patient can view his personal details.
 Disease Prediction: - Patient will specify the symptoms caused due to his illness. System will ask
certain question regarding his illness and system predict the disease based on the symptoms
specified by the patient and system will also suggest doctors based on the disease.
 Search Doctor:- Patient can search for doctor by specifying name, address or type.
 Feedback:-Patient will give feedback this will be reported to the admin.
 Doctor Login: - Doctor will access the system using his User ID and Password.
 Patient Details: Doctor can view patient’s personal details.
 Notification: Doctor will get notification how many people had accessed the system and what all
are the diseases predicted by the system.
 Admin Login: Admin can login to the system using his ID and Password.
 Add Doctor: Admin can add new doctor details into the database.
 Add Dataset: Admin can add dataset file (which contains disease details along with symptoms) in
database.
 Add Disease: Admin can add disease details along with symptoms and type.
 View Doctor: Admin can view various Doctors along with their personal details.
 View Disease: Admin can view various diseases details stored in database.
 View Patient: Admin can view various patient details who had accessed the system.
 View Feedback: Admin can view feedback provided by various users.

7
ADVANTAGES OF PROPOSED SYSTEM

The system is very simple in design and to implement. The system requires very low system
resources and the system will work in almost all configurations. It has got following features

 Save time of customers in quickly reserving all the facility of online booking.
 The ability to purchase clay products any time, from anywhere with internet access.
 Provide the information about products and its information.
 User friendly
Better security: -

For data to remain secure measures must be taken to prevent unauthorized access. Security
means that data are protected from various forms of destruction. The system security problem
can be divided into four related issues: security, integrity, privacy and confidentiality. Username
and password requirement to sign in ensures security. It will also provide data security as we are
using the secured databases for maintaining the documents.

Ensure data accuracy: -

The proposed system eliminates the manual errors while entering the details of the users during
the registration.

Better service: -

The product will avoid the burden of hard copy storage. We can also conserve the time and
human resources for doing the same task. The data can be maintained for longer period with no
loss of data.

User friendliness and interactive: -

The proposed system’s interface help the users to perform their operations without any
confusions or difficulties. A customer can easily find their interested products and can able to
purchase

8
1.3 FEASIBILITY ANALYSIS

Feasibility study is made to see if the project on completion will serve the purpose of the
organization for the amount of work, effort and the time that spend on it. Feasibility study lets
the developer foresee the future of the project and the usefulness. A feasibility study of a system
proposal is according to its workability, which is the impact on the organization, ability to meet
their user needs and effective use of resources. Thus, when a new application is proposed it
normally goes through a feasibility study before it is approved for development.

The document provides the feasibility of the project that is being designed and lists various areas
that were considered very carefully during the feasibility study of this project such as Technical,
Economic and Operational feasibilities. The following are its features: -

Economical Feasibility

The developing system must be justified by cost and benefit. Criteria to ensure that effort is
concentrated on project, which will give best, return at the earliest. One of the factors, which
affect the development of a new system, is the cost it would require.

The following are some of the important financial questions asked during preliminary
investigation:

 The costs conduct a full system investigation.


 The cost of the hardware and software.
 The benefits in the form of reduced costs or fewer costly errors.

User friendliness is provided in the application with various controls.


The system makes the overall project management much easier and flexible.
There is no risk of data mismanagement at any level while the project development is under
process.
It provides high level of security with different level of authentication.

The system must be evaluated from the technical point of view first. The assessment of this
feasibility must be based on an outline design of the system requirement in the terms of input,
output, programs and procedures. Having identified an outline system, the investigation must go
on to suggest the type of equipment, required method developing the system, of running the
system once it has been designed.

Technical issues raised during the investigation are:

9
 Does the existing technology sufficient for the suggested one?
 Can the system expand if developed?

The project should be developed such that the necessary functions and performance are achieved
within the constraints. The project requires High Resolution Scanning device and utilizes
Cryptographic techniques. Through the technology may become obsolete after some period of
time, due to the fact that newer version of same software supports older versions, the system may
still be used. So there are minimal constraints involved with this project. The system has been
developed using HTML, CSS in front end and Sqlite3 in server in back end, the project is
technically feasible for development. The system has been developed using HTML, CSS, Python
and Sqlite3 in server back end, the project is technically feasible for development. The System used
was also of good performance of Processor Intel i3 core; RAM 4GB and, Hard disk 1TB

Behavioral Feasibility

The proposed system includes the following questions:

 Is there sufficient support for the users?


 Will the proposed system cause harm?

The project would be beneficial because it satisfies the objectives when developed and installed.
All behavioral aspects are considered carefully and conclude that the project is behaviorally
feasible.

10
2.5 SOFTWARE ENGINEERING PARADIGM APPLIED

Its framework which will be used to finish as well as execute the project would be explained in detail
in this chapter. The methodology will be based on the System Development Life Cycle (SDLC) order
to evaluate and advance this project

 Planning
 Implementing
 Analyzing Waterfall Model

2.5.1 PRELIMINARY ANALYSIS

The objective of phase 1 is to conduct a preliminary analysis, propose alternative solutions, describe
costs and benefits and submit a preliminary plan with recommendations.

 Conduct the preliminary analysis: in this step, you need to find out the organization's

11
objectives and the nature and scope of the problem under study. Even if a problem refers
onlyto a small segment of the organization itself, you need to find out what the objectives of
the organization itself are. Then you need to see how the problem being studied fits in with
them.

 Propose alternative solutions: In digging into the organization's objectives and specific
problems, you may have already covered some solutions. Alternate proposals may come from
interviewing employees, clients, suppliers, and/or consultants. You can also study what
competitors are doing. With this data, you will have three choices: leave the system as is,
improve it, or develop a new system.

 Describe the costs and benefits. Systems analysis, requirements definition: Defines project
goals into defined functions and operation of the intended application. It is the process of
gathering and interpreting facts, diagnosing problems and recommending improvements to the
system.

Analyzes end-user information needs and also removes any inconsistencies and incompleteness in
these requirements. A series of steps followed are:

 Collection of Facts: End user requirements are obtained through documentation, client
interviews, observation and questionnaires.

 Scrutiny of the existing system: Identify pros and cons of the current system in- place, so as to
carry forward the pros and avoid the cons in the new system.

 Analyzing the proposed system: Solutions to the shortcomings in step two are found and any
specific user proposals are used to prepare the specifications.

12
Systems design:

Describes desired features and operations in detail, including screen layouts, business rules, process
diagrams, pseudocode and other documentation.

Development:

The real code is written here.

Integration and testing:

Brings all the pieces together into a special testing environment, then checks for errors, bugs and
interoperability.

Acceptance, installation, deployment:

The final stage of initial development, where the software is put into production and runs actual
business.

Maintenance:

During the maintenance stage of the SDLC, the system is assessed to ensure it does not become
obsolete. This is also where changes are made to initial software.
It involves continuous evaluation of the system in terms of its performance.

13
14
CHAPTER 3
SYSTEM DESIGN

15
SYSTEM DESIGN
INTRODUCTION

Design is the first step into the development phase for any engineered product or system.
Design is a creative process. A good design is the key to effective system. The term “design” is
defined as “the process of applying various techniques and principles for the purpose of defining
a process or a system in sufficient detail to permit its physical realization”. It may be defined as a
process of applying various techniques and principles for the purpose of defining a device, a
process or a system in sufficient detail to permit its physical realization. Software design sits at
the technical kernel of the software engineering process and is applied regardless of the
development paradigm that is used. The system design develops the architectural detail required
to build a system or product. As in the case of any systematic approach, this software too has
undergone the best possible design phase fine tuning all efficiency, performance and accuracy
levels. The design phase is a transition from a user oriented document to a document to the
programmers or database personnel. System design goes through two phases of development:
Logical and Physical Design.

16
3.2 DATABASE DESIGN

A database is an organized mechanism that has the capability of storing information through
which a user can retrieve stored information in an effective and efficient manner. The data is the
purpose of any database and must be protected.

The database design is a two level process. In the first step, user requirements are gathered
together and a database is designed which will meet these requirements as clearly as possible.
This step is called Information Level Design and it is taken independent of any individual
DBMS.

In the second step, this Information level design is transferred into a design for the specific
DBMS that will be used to implement the system in question. This step is called Physical Level
Design, concerned with the characteristics of the specific DBMS that will be used. A database
design runs parallel with the system design. The organization of the data in the database is aimed
to achieve the following two major objectives.

 Data Integrity
 Data independence

Relational Database Management System (RDBMS)

A relational model represents the database as a collection of relations. Each relation resembles a
table of values or file of records. In formal relational model terminology, a row is called a
tuplea column header is called an attribute and the table is called a relation. A relational database
consists of a collection of tables, each of which is assigned a unique name. A row in a tale
represents a set of related values.

Relations, Domains & Attributes

A table is a relation. The rows in a table are called tuples. A tuple is an ordered set of n elements.
Columns are referred to as attributes. Relationships have been set between every table in the
database. This ensures both Referential and Entity Relationship Integrity. A domain D is a set of
atomic values. A common method of specifying a domain is to specify a data type from which
17
the data values forming the domain are drawn. It is also useful to specify a name for the domain
to help in interpreting its values.

Every value in a relation is atomic, that is not decomposable.

Relationships

 Table relationships are established using Key. The two main keys of prime importance
are Primary Key & Foreign Key. Entity Integrity and Referential Integrity Relationships
can be established with these keys.
 Entity Integrity enforces that no Primary Key can have null values.
 Referential Integrity enforces that no Primary Key can have null values.
 Referential Integrity for each distinct Foreign Key value, there must exist a matching
Primary Key value in the same domain. Other key are Super Key and Candidate Keys.

Normalization

Data are grouped together in the simplest way so that later changes can be made with minimum
impact on data structures. Normalization is formal process of data structures in manners that
eliminates redundancy and promotes integrity. Normalization is a technique of separating
redundant fields and breaking up a large table into a smaller one. It is also used to avoid
insertion, deletion, and updating anomalies.

Normal form in data modelling use two concepts, keys and relationships. A key uniquely
identifies a row in a table.

There are two types of keys, primary key and foreign key. A primary key is an element or a
combination of elements in a table whose purpose is to identify records from the same table. A
foreign key is a column in a table that uniquely identifies record from a different table. All the
tables have been normalized up to the third normal form.

As the name implies, it denotes putting things in the normal form. The application developer via
normalization tries to achieve a sensible organization of data into proper tables and columns and
where names can be easily correlated to the data by the user. Normalization eliminates repeating
18
groups at data and thereby avoids data redundancy which proves to be a great burden on the
computer resources. These include:

 Normalize the data.


 Choose proper names for the tables and columns.
 Choose the proper name for the data.

First Normal Form

The First Normal Form states that the domain of an attribute must include only atomic values
and that the value of any attribute in a tuple must be a single value from the domain of that
attribute. In other words 1NF disallows “relations within relations” or “relations as attribute
values within tuples”. The only attribute values permitted by 1NF are single atomic or indivisible
values. The first step is to put the data into First Normal Form. This can be donor by moving data
into separate tables where the data is of similar type in each table. Each table is given a Primary
Key or Foreign Key as per requirement of the project. In this we form new relations for each
non-atomic attribute or nested relation. This eliminated repeating groups of data. A relation is
said to be in first normal form if only if it satisfies the constraints that contain the primary key
only.

Second Normal Form

According to Second Normal Form, for relations where primary key contains multiple attributes,
no non-key attribute should be functionally dependent on a part of the primary key. In this we
decompose and setup a new relation for each partial key with its dependent attributes. Make sure
to keep a relation with the original primary key and any attributes that are fully functionally
dependent on it. This step helps in taking out data that is only dependent on a part of the key.

A relation is said to be in second normal form if and only if it satisfies all the first normal form

19
conditions for the primary key and every non-primary key attributes of the relation is fully
dependent on its primary key alone.

Third Normal Form

According to Third Normal Form, Relation should not have a non-key attribute functionally
determined by another non-key attribute or by a set of non-key attributes. That is, there should be
no transitive dependency on the primary key. In this we decompose and set up relation that
includes the non-key attributes that functionally determines other non-key attributes. This step is
taken to get rid of anything that does not depend entirely on the Primary Key. A relation is said
to be in third normal form if only if it is in second normal form and more over the non key
attributes of the relation should not be depend on other non-key attribute.

20
3.2.1 Entity Relationship Diagrams (ER-Diagrams):

An entity-relationship (ER) diagram is a specialized graphic that illustrates the interrelationships


between entities in a database. ER diagrams often use symbols to represent three different types of
information. Boxes are commonly used to represent entities. Diamonds are normally used to
represent relationships and ovals are used to represent attributes
An entity-relationship model (ERM) in software engineering is an abstract and conceptual
representation of data. Entity-relationship modeling is a relational schema database modeling
method, used to produce a type of conceptual schema or semantic data model of a system, often a
relational database, and its requirements in a top-down fashion.

Symbols used in this E-R Diagram:

Entity: Entity is a “thing” in the real world with an independent existence. An entity may be an
object with a physical existence such as person, car or employee. Entity symbol is as follows

Attribute: Attribute is a particular property that describes the entity. Attribute symbol is

Relationship: Relationship will be several implicit relationships among various entity types whenever
an attribute of one entity refers to another entity type some relationship exits. Relationship symbol is:

21
Key attributes: An entity type usually has an attribute whose values are distinct for each individual
entity in the collection. Such an attribute is called key attribute.

22
3.2.2 PROCESS DESIGN – DATA FLOW DIAGRAM

Data Flow Diagram

A Data Flow Diagram (DFD) is a graphical representation of the "flow" of data through an
Information System. A data flow diagram can also be used for the visualization of Data Processing. It
is common practice for a designer to draw a context-level DFD first which shows the interaction
between the system and outside entities. This context-level DFD is then "exploded" to show more
detail of the system being modeled.

A DFD represents flow of data through a system. Data flow diagrams are commonly used during
problem analysis. It views a system as a function that transforms the input into desired output. A DFD
shows movement of data through the different transformations or processes in the system.

Dataflow diagrams can be used to provide the end user with a physical idea of where the data they
input ultimately has an effect upon the structure of the whole system from order to dispatch to restock
how any system is developed can be determined through a dataflow diagram. The appropriate register
saved in database and maintained by appropriate authorities.

Data Flow Diagram Notation

Function

File/Database

Input/output

23
Flow

LEVEL O DFD

LEVEL 1 DFD

24
LEVEL 2 DFD

25
3.3 OBJECT ORIENTED DESIGN – UML DIAGRAMS

3.3.1 SEQUENCE DIAGRAM

Login Application Database

Login
:Request

:Validate()
:executeQuery()

Response
Show Result

Failed:show()

26
Login Application Database

Login
:Request

:Validate()
:executeQuery()

Response
Show Result

27
3.3.2 USECASE DIAGRAM

A use case diagram is used to represent the dynamic behavior of a system. It encapsulates the
system's functionality by incorporating use cases, actors, and their relationships. It models the
tasks, services, and functions required by a system/subsystem of an application. It depicts the high-
level functionality of a system and also tells how the user handles a system.

The main purpose of a use case diagram is to portray the dynamic aspect of a system. It
accumulates the system's requirement, which includes both internal as well as external influences.
It invokes persons, use cases, and several things that invoke the actors and elements accountable
for the implementation of use case diagrams. It represents how an entity from the external
environment can interact with a part of the system.

28
29
3.4.3 CLASS DIAGRAM

30
3.4 DATABASE DESIGN

31
1. Table Name: Profile

2. Table Name:Predict

3. Table Name: Donatiom


32
4. Table Name:Feedback

5. Table Name: Doctor


33
6. Table Name: search data

7. Table Name: generalhealthpredict

34
3.6 MODULE DESCRIPTION

Admin Modules

1. Dashboard: In this section admin can see all detail in brief like total number of patients, Total
number of appointments, Rejected Appointment, Accepted Appointment, total doctors etc.
2. Appointment: In this section admin can view the detail of appointments and have right to
reject and select appointment.
3. Patient: In this section admin can mange patient (add/update).
4. Patient List: In this section admin can view patients list make invoices of bill.
5. Doctor: In this section admin can mange doctor (add/update).
6. Doctor List: In this section admin can view doctors list.
7. Invoice: In this section there is the list of total invoices which is viewed by admin
8. Search Appointment: In this section admin can search appointment with the help of his/her
appointment number, name and contact number.
9. Search Invoice: In this section admin can search invoices with the help of his/her invoice
number.
Admin can also update his profile, change password and recover password.

User (Patient) Modules

1. In hospital management system project patient requires to signin


2. Appointment: Patient can take appointment with doctor on particular date and time.
3. Search: Patient can search doctor via name, speciality and location.
4. View Prescription: Patient can view the prescriptions given by doctor.
5. Patient can also update his profile and change password.

User (Doctor) Modules

1. In hospital management system project doctor requires to sign in.


35
2. Appointment: Doctor can view our appointment details.
3. Prescription: Doctor can write prescriptions to patients.
4. View Patients: Doctor can view the patient details.
5. Doctor can also update his profile and change password.

36
3.7 INPUT DESIGN

In an information system, input is the raw data that is processed to produce output. During the input
design, the developers must consider the input devices such as PC, MICR, OMR, etc.
Therefore, the quality of system input determines the quality of system output. Well designed input
forms and screens have following properties −
 It should serve specific purpose effectively such as storing, recording, and retrieving the
information.
 It ensures proper completion with accuracy.
 It should be easy to fill and straightforward.
 It should focus on user’s attention, consistency, and simplicity.
 All these objectives are obtained using the knowledge of basic design principles regarding −
 What are the inputs needed for the system?
 How end users respond to different elements of forms and screens.

3.8 OUTPUT DESIGN

Computer output is the most important and direct source of information to the user. The output should
be efficient and intelligible and help the user in decision-making. A major form of output is a hard
copy from computer. Printout should be designed around the output requirements of the user. The
following media devices are available for providing computer-based output In addition to deciding on
the output device the systems analyst must consider the print format and the editing for the final
printout. Editing ranges from suppressing zeroes to merging selected records.

37
38
39
CHAPTER 4

SYSTEM ENVIRONMENT

40
4.1 INTRODUCTION

The project environment artifacts evolve through three discrete states: the prototyping environment,
the development environment, and the maintenance environment. The transition to a mature software
process introduces new challenges and opportunities for management control of concurrent activities
and for assessment of tangible progress and quality. Real-world project experience has shown that a
highly integrated environment is necessary both to facilitate and to enforce management control of the
process. Toward this end, there are four important environment disciplines that are critical to the
management context and the success of a modern iterative development process:

4.2 TOOLS/PLATFORM, HARDWARE & SOFTWARE REQUIREMENTS

4.2.1 SOFTWARE REQUIREMENTS

 Technology: Python Django, Machine Learning


 IDE : Pycharm/Atom
 Client Side Technologies: HTML, CSS, JavaScript , Bootstrap
 Server Side Technologies: Python
 Data Base Server: Sqlite, Kaggel Dataset
 Operating System: Microsoft Windows/Linux

4.2.2 HARDWARE REQUIREMENTS

 Processor: Pentium-III (or) Higher


 Ram: 64MB (or) Higher
 Hard disk: 80GB (or) Higher

41
HTML

HTML (Hypertext Markup Language) is the set of markup symbols or codes inserted in a file intended for
display on a World Wide Web browser page. The markup tells the Web browser how to display a Web page's
words and images for the user. Each individual markup code is referred to as an element (but many people also
refer to it as a tag). Some elements come in pairs that indicate when some display effect is to begin and when it
is to end.

CASCADING STYLE SHEET (CSS)

Cascading Style Sheets (CSS) are a collection of rules we use to define and modify web pages. CSS are similar
to styles in Word. CSS allow Web designers to have much more control over their pages look and layout. For
instance, you could create a style that defines the body text to be Verdana, 10 point. Later on, you may easily
change the body text to Times New Roman, 12 point by just changing the rule in the CSS. Instead of having to
change the font on each page of your website, all you need to do is redefine the style on the style sheet, and it
will instantly change on all of the pages that the style sheet has been applied to. With HTML styles, the font
change would be applied to each instance of that font and have to be changed in each spot.

CSS can control the placement of text and objects on your pages as well as the look of those objects.

HTML information creates the objects (or gives objects meaning), but styles describe how the objects should
appear. The HTML gives your page structure, while the CSS creates the “presentation”. An external CSS is
really just a text file with a .css extension. These files can be created with Dreamweaver, a CSS editor, or even
Notepad.

The best practice is to design your web page on paper first so you know where you will want to use styles on
your page. Then you can create the styles and apply them to your page.

Javascript

JavaScript is a programming language commonly used in web development. It was originally


developed by Netscape as a means to add dynamic and interactive elements to websites. While
42
JavaScript is influenced byJava, the syntax is more similar to C and is based on ECMAScript, a
scripting language developed by Sun Microsystems.
JavaScript is a client-side scripting language, which means the source code is processed by the
client's web browser rather than on the web server. This means JavaScript functions can run after a
webpage has loaded without COMMUNICATING with the server. For example, a JavaScript function
may check a web form before it is submitted to make sure all the required fields have been filled out.
The JavaScript code can produce an error message before any information is actually transmitted to
the server.
Like server-side scripting languages, such as PHP and ASP, JavaScript code can be inserted anywhere
within the HTML of a webpage. However, only the output of server-side code is displayed in the
HTML, while JavaScript code remains fully visible in the source of the webpage. It can also be
referenced in a separate .JS file, which may also be viewed in a browser.

PYTHON

Python is a widely used general-purpose, high level programming language. It was initially designed
by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly
developed for emphasis on code readability, and its syntax allows programmers to express concepts in
fewer lines of code.
Python is dynamically typed and garbage-collected. It supports multiple programming paradigms,
including procedural, object- Python is a programming language that lets you work quickly and
integrate systems more efficiently.
oriented, and functional programming. Python is often described as a "batteries included" language
due to its comprehensive standard library.

Django

43
Django is a web application framework written in Python programming language. It is based on MVT
(Model View Template) design pattern. The Django is very demanding due to its rapid development
feature. It takes less time to build application after collecting client requirement.

This framework uses a famous tag line: The web framework for perfectionists with deadlines.

HTML

HTML (Hypertext Markup Language) is the set of markup symbols or codes inserted in a file intended
for display on a World Wide Web browser page. The markup tells the Web browser how to display a
Web page's words and images for the user. Each individual markup code is referred to as an element
(but many people also refer to it as a tag). Some elements come in pairs that indicate when some
display effect is to begin and when it is to end

CASCADING STYLE SHEET (CSS)

Cascading Style Sheets (CSS) are a collection of rules we use to define and modify web pages. CSS are similar
to styles in Word. CSS allow Web designers to have much more control over their pages look and layout. For
instance, you could create a style that defines the body text to be Verdana, 10 point. Later on, you may easily
change the body text to Times New Roman, 12 point by just changing the rule in the CSS. Instead of having to
change the font on each page of your website, all you need to do is redefine the style on the style sheet, and it
will instantly change on all of the pages that the style sheet has been applied to. With HTML styles, the font
change would be applied to each instance of that font and have to be changed in each spot.

CSS can control the placement of text and objects on your pages as well as the look of those objects.

HTML information creates the objects (or gives objects meaning), but styles describe how the objects should
appear. The HTML gives your page structure, while the CSS creates the “presentation”. An external CSS is
really just a text file with a .css extension. These files can be created with Dreamweaver, a CSS editor, or even
Notepad.

The best practice is to design your web page on paper first so you know where you will want to use styles on
your page. Then you can create the styles and apply them to your page.
44
Javascript

JavaScript is a programming language commonly used in web development. It was originally


developed by Netscape as a means to add dynamic and interactive elements to websites. While
JavaScript is influenced byJava, the syntax is more similar to C and is based on ECMAScript, a
scripting language developed by Sun Microsystems.
JavaScript is a client-side scripting language, which means the source code is processed by the
client's web browser rather than on the web server. This means JavaScript functions can run after a
webpage has loaded without COMMUNICATING with the server. For example, a JavaScript function
may check a web form before it is submitted to make sure all the required fields have been filled out.
The JavaScript code can produce an error message before any information is actually transmitted to
the server.
Like server-side scripting languages, such as PHP and ASP, JavaScript code can be inserted anywhere
within the HTML of a webpage. However, only the output of server-side code is displayed in the
HTML, while JavaScript code remains fully visible in the source of the webpage. It can also be
referenced in a separate .JS file, which may also be viewed in a browser.

4.5 OPERATING SYSTEM

An operating system (OS) is the program that, after being initially loaded into the computer by a boot
program, manages all of the other application programs in a computer. The application programs make
use of the operating system by making requests for services through a defined application program
interface (API). In addition, users can interact directly with the operating system through a user
interface, such as a command-line interface (CLI) or a graphical UI (GUI).

An operating system brings powerful benefits to computer software and software development.
Without an operating system, every application would need to include its own UI, as well as the
comprehensive code needed to handle all low-level functionality of the underlying computer, such as
45
disk storage, network interfaces and so on. Considering the vast array of underlying hardware
available, this would vastly bloat the size of every application and make software development
impractical.

Algorithm
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
import datetime

from sklearn.ensemble import GradientBoostingClassifier

from .forms import DoctorForm


from .models import *
from django.contrib.auth import authenticate, login, logout
import numpy as np
import pandas as pd

import matplotlib.pyplot as plt


import seaborn as sns
sns.set_style('darkgrid')

from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler


from sklearn.model_selection import train_test_split

from sklearn.linear_model import LogisticRegression


from sklearn.svm import SVC
from sklearn.neural_network import MLPClassifier
from django.http import HttpResponse, HttpResponseRedirect
# Create your views here.
46
from pickle import encode_long
import numpy as np
import pandas as pd
from scipy.stats import mode
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.svm import SVC
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, confusion_matrix

def Home(request):
return render(request,'carousel.html')

def Admin_Home(request):
dis = Search_Data.objects.all()
pat = Patient.objects.all()
doc = Doctor.objects.all()
feed = Feedback.objects.all()

d = {'dis':dis.count(),'pat':pat.count(),'doc':doc.count(),'feed':feed.count()}
return render(request,'admin_home.html',d)

@login_required(login_url="login")
def assign_status(request,pid):
doctor = Doctor.objects.get(id=pid)

47
if doctor.status == 1:
doctor.status = 2
messages.success(request, 'Selected doctor are successfully withdraw his approval.')
else:
doctor.status = 1
messages.success(request, 'Selected doctor are successfully approved.')
doctor.save()
return redirect('view_doctor')

@login_required(login_url="login")
def User_Home(request):
return render(request,'patient_home.html')

@login_required(login_url="login")
def Doctor_Home(request):
return render(request,'doctor_home.html')

def About(request):
return render(request,'about.html')

def Contact(request):
return render(request,'contact.html')

def Gallery(request):
return render(request,'gallery.html')

def Login_User(request):
error = ""
if request.method == "POST":

48
u = request.POST['uname']
p = request.POST['pwd']
user = authenticate(username=u, password=p)
sign = ""
if user:
try:
sign = Patient.objects.get(user=user)
except:
pass
if sign:
login(request, user)
error = "pat1"
else:
pure=False
try:
pure = Doctor.objects.get(status=1,user=user)
except:
pass
if pure:
login(request, user)
error = "pat2"
else:
login(request, user)
error="notmember"
else:
error="not"
d = {'error': error}
return render(request, 'login.html', d)

def Login_admin(request):
error = ""

49
if request.method == "POST":
u = request.POST['uname']
p = request.POST['pwd']
user = authenticate(username=u, password=p)
if user.is_staff:
login(request, user)
error="pat"
else:
error="not"
d = {'error': error}
return render(request, 'admin_login.html', d)

def Signup_User(request):
error = ""
if request.method == 'POST':
f = request.POST['fname']
l = request.POST['lname']
u = request.POST['uname']
e = request.POST['email']
p = request.POST['pwd']
d = request.POST['dob']
con = request.POST['contact']
add = request.POST['add']
type = request.POST['type']
im = request.FILES['image']
dat = datetime.date.today()
user = User.objects.create_user(email=e, username=u, password=p, first_name=f,last_name=l)
if type == "Patient":
Patient.objects.create(user=user,contact=con,address=add,image=im,dob=d)
else:
Doctor.objects.create(dob=d,image=im,user=user,contact=con,address=add,status=2)

50
error = "create"
d = {'error':error}
return render(request,'register.html',d)

def Logout(request):
logout(request)
return redirect('home')

@login_required(login_url="login")
def Change_Password(request):
sign = 0
user = User.objects.get(username=request.user.username)
error = ""
if not request.user.is_staff:
try:
sign = Patient.objects.get(user=user)
if sign:
error = "pat"
except:
sign = Doctor.objects.get(user=user)
terror = ""
if request.method=="POST":
n = request.POST['pwd1']
c = request.POST['pwd2']
o = request.POST['pwd3']
if c == n:
u = User.objects.get(username__exact=request.user.username)
u.set_password(n)
u.save()
terror = "yes"
else:

51
terror = "not"
d = {'error':error,'terror':terror,'data':sign}
return render(request,'change_password.html',d)

def preprocess_inputs(df, scaler):


df = df.copy()
# Split df into X and y
y = df['target'].copy()
X = df.drop('target', axis=1).copy()
X = pd.DataFrame(scaler.fit_transform(X), columns=X.columns)
return X, y

def prdict_heart_disease(list_data):
csv_file = Admin_Helath_CSV.objects.get(id=1)
df = pd.read_csv(csv_file.csv_file)

X = df[['age','sex','cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thalach', 'exang', 'oldpeak', 'slope', 'ca',
'thal']]
y = df['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8, random_state=0)
nn_model = GradientBoostingClassifier(n_estimators=100,learning_rate=1.0,max_depth=1,
random_state=0)
nn_model.fit(X_train, y_train)
pred = nn_model.predict([list_data])
print("Neural Network Accuracy: {:.2f}%".format(nn_model.score(X_test, y_test) * 100))
print("Prdicted Value is : ", format(pred))
dataframe = str(df.head())
return (nn_model.score(X_test, y_test) * 100),(pred)

52
@login_required(login_url="login")
def add_doctor(request,pid=None):
doctor = None
if pid:
doctor = Doctor.objects.get(id=pid)
if request.method == "POST":
form = DoctorForm(request.POST, request.FILES, instance = doctor)
if form.is_valid():
new_doc = form.save()
new_doc.status = 1
if not pid:
user = User.objects.create_user(password=request.POST['password'],
username=request.POST['username'], first_name=request.POST['first_name'],
last_name=request.POST['last_name'])
new_doc.user = user
new_doc.save()
return redirect('view_doctor')
d = {"doctor": doctor}
return render(request, 'add_doctor.html', d)

@login_required(login_url="login")
def add_heartdetail(request):
if request.method == "POST":
# list_data = [57, 0, 1, 130, 236, 0, 0, 174, 0, 0.0, 1, 1, 2]
list_data = []
value_dict = eval(str(request.POST)[12:-1])
count = 0
for key,value in value_dict.items():
if count == 0:
count =1
continue

53
if key == "sex" and value[0] == "Male" or value[0] == 'male' or value[0]=='m' or value[0] ==
'M':
list_data.append(0)
continue
elif key == "sex":
list_data.append(1)
continue
list_data.append(value[0])

# list_data = [57, 0, 1, 130, 236, 0, 0, 174, 0, 0.0, 1, 1, 2]


accuracy,pred = prdict_heart_disease(list_data)
patient = Patient.objects.get(user=request.user)
Search_Data.objects.create(patient=patient, prediction_accuracy=round(accuracy,2),
result=pred[0], values_list=list_data,predict_for="Heart Prediction")
rem = int(pred[0])
print("Result = ",rem)
if pred[0] == 0:
pred = "<span style='color:green'>You are healthy</span>"
else:
pred = "<span style='color:red'>You are Unhealthy, Need to Checkup.</span>"
return redirect('predict_desease', str(rem), str(round(accuracy,2)))
return render(request, 'add_heartdetail.html')

@login_required(login_url="login")
def predict_desease(request, pred, accuracy):
doctor = Doctor.objects.filter(address__icontains=Patient.objects.get(user=request.user).address)
d = {'pred': pred, 'accuracy':accuracy, 'doctor':doctor}
return render(request, 'predict_disease.html', d)

@login_required(login_url="login")
def view_search_pat(request):

54
doc = None
try:
doc = Doctor.objects.get(user=request.user)
data = Search_Data.objects.filter(patient__address__icontains=doc.address).order_by('-id')
except:
try:
doc = Patient.objects.get(user=request.user)
data = Search_Data.objects.filter(patient=doc).order_by('-id')
except:
data = Search_Data.objects.all().order_by('-id')
return render(request,'view_search_pat.html',{'data':data})

@login_required(login_url="login")
def delete_doctor(request,pid):
doc = Doctor.objects.get(id=pid)
doc.delete()
return redirect('view_doctor')

@login_required(login_url="login")
def delete_feedback(request,pid):
doc = Feedback.objects.get(id=pid)
doc.delete()
return redirect('view_feedback')

@login_required(login_url="login")
def delete_patient(request,pid):
doc = Patient.objects.get(id=pid)
doc.delete()
return redirect('view_patient')

@login_required(login_url="login")

55
def delete_searched(request,pid):
doc = Search_Data.objects.get(id=pid)
doc.delete()
return redirect('view_search_pat')

@login_required(login_url="login")
def View_Doctor(request):
doc = Doctor.objects.all()
d = {'doc':doc}
return render(request,'view_doctor.html',d)

@login_required(login_url="login")
def View_Patient(request):
patient = Patient.objects.all()
d = {'patient':patient}
return render(request,'view_patient.html',d)

@login_required(login_url="login")
def View_Feedback(request):
dis = Feedback.objects.all()
d = {'dis':dis}
return render(request,'view_feedback.html',d)

@login_required(login_url="login")
def View_My_Detail(request):
terror = ""
user = User.objects.get(id=request.user.id)
error = ""
try:
sign = Patient.objects.get(user=user)
error = "pat"

56
except:
sign = Doctor.objects.get(user=user)
d = {'error': error,'pro':sign}
return render(request,'profile_doctor.html',d)

@login_required(login_url="login")
def Edit_Doctor(request,pid):
doc = Doctor.objects.get(id=pid)
error = ""
# type = Type.objects.all()
if request.method == 'POST':
f = request.POST['fname']
l = request.POST['lname']
e = request.POST['email']
con = request.POST['contact']
add = request.POST['add']
cat = request.POST['type']
try:
im = request.FILES['image']
doc.image=im
doc.save()
except:
pass
dat = datetime.date.today()
doc.user.first_name = f
doc.user.last_name = l
doc.user.email = e
doc.contact = con
doc.category = cat
doc.address = add
doc.user.save()

57
doc.save()
error = "create"
d = {'error':error,'doc':doc,'type':type}
return render(request,'edit_doctor.html',d)

@login_required(login_url="login")
def Edit_My_deatail(request):
terror = ""
print("Hii welvome")
user = User.objects.get(id=request.user.id)
error = ""
# type = Type.objects.all()
try:
sign = Patient.objects.get(user=user)
error = "pat"
except:
sign = Doctor.objects.get(user=user)
if request.method == 'POST':
f = request.POST['fname']
l = request.POST['lname']
e = request.POST['email']
con = request.POST['contact']
add = request.POST['add']
try:
im = request.FILES['image']
sign.image = im
sign.save()
except:
pass
to1 = datetime.date.today()
sign.user.first_name = f

58
sign.user.last_name = l
sign.user.email = e
sign.contact = con
if error != "pat":
cat = request.POST['type']
sign.category = cat
sign.save()
sign.address = add
sign.user.save()
sign.save()
terror = "create"
d = {'error':error,'terror':terror,'doc':sign}
return render(request,'edit_profile.html',d)

@login_required(login_url='login')
def sent_feedback(request):
terror = None
if request.method == "POST":
username = request.POST['uname']
message = request.POST['msg']
username = User.objects.get(username=username)
Feedback.objects.create(user=username, messages=message)
terror = "create"
return render(request, 'sent_feedback.html',{'terror':terror})

def add_genralhealth(request):
predictiondata = None
deseaseli = []
if request.method=="POST":
for i,j in request.POST.items():

59
if "csrfmiddlewaretoken" != i:
deseaseli.append(i)
# training.csv
DATA_PATH = Admin_Helath_CSV.objects.get(id=2)
#df = pd.read_csv(csv_file.csv_file)
#DATA_PATH = "c:/Users/bhuwa/OneDrive/Desktop/dataset/Training.csv"
data = pd.read_csv(DATA_PATH.csv_file).dropna(axis = 1)

# Checking whether the dataset is balanced or not


disease_counts = data["prognosis"].value_counts()
temp_df = pd.DataFrame({
"Disease": disease_counts.index,
"Counts": disease_counts.values
})

plt.figure(figsize = (18,8))
sns.barplot(x = "Disease", y = "Counts", data = temp_df)
plt.xticks(rotation=90)
# plt.show()

# Encoding the target value into numerical


# value using LabelEncoder
encoder = LabelEncoder()
data["prognosis"] = encoder.fit_transform(data["prognosis"])

X = data.iloc[:,:-1]
y = data.iloc[:, -1]
X_train, X_test, y_train, y_test =train_test_split(
X, y, test_size = 0.2, random_state = 24)

60
symptoms = X.columns.values
symptom_index = {}
for index, value in enumerate(symptoms):
symptom = " ".join([i.capitalize() for i in value.split("_")])
symptom_index[symptom] = index

data_dict = {
"symptom_index":symptom_index,
"predictions_classes":encoder.classes_
}

final_svm_model = SVC()
final_nb_model = GaussianNB()
final_rf_model = RandomForestClassifier(random_state=18)
final_svm_model.fit(X, y)
final_nb_model.fit(X, y)
final_rf_model.fit(X, y)

#Testing.csv
DATA_PATH2 = Admin_Helath_CSV.objects.get(id=3)
test_data = pd.read_csv(DATA_PATH2.csv_file).dropna(axis=1)

test_X = test_data.iloc[:, :-1]


test_Y = encoder.transform(test_data.iloc[:, -1])

svm_preds = final_svm_model.predict(test_X)
nb_preds = final_nb_model.predict(test_X)
rf_preds = final_rf_model.predict(test_X)

61
final_preds = [mode([i,j,k])[0][0] for i,j,
k in zip(svm_preds, nb_preds, rf_preds)]

print(f"Accuracy on Test dataset by the combined model\


: {accuracy_score(test_Y, final_preds)*100}")

cf_matrix = confusion_matrix(test_Y, final_preds)


plt.figure(figsize=(12,8))

sns.heatmap(cf_matrix, annot = True)


# plt.title("Confusion Matrix for Combined Model on Test Dataset")
# # plt.show()

def predictDisease(symptoms):
# print("All Symptoms = ", symptoms)
# symptoms = symptoms.split(",")

# # creating input data for the models


input_data = [0] * len(data_dict["symptom_index"])
for symptom in symptoms:
index = data_dict["symptom_index"][symptom]
input_data[index] = 1

# reshaping the input data and converting it


# into suitable format for model predictions
input_data = np.array(input_data).reshape(1,-1)

# generating individual outputs


rf_prediction = data_dict["predictions_classes"][final_rf_model.predict(input_data)[0]]
nb_prediction = data_dict["predictions_classes"][final_nb_model.predict(input_data)[0]]
svm_prediction = data_dict["predictions_classes"][final_svm_model.predict(input_data)[0]]

62
# making final prediction by taking mode of all predictions
final_prediction = mode([rf_prediction, nb_prediction, svm_prediction])[0][0]
predictions = {
"RandomForestClassifier Prediction": rf_prediction,
"GaussianNB Prediction": nb_prediction,
"SVC Prediction": svm_prediction,
"Final Prediction":final_prediction
}
return predictions

# Testing the function


predictiondata = predictDisease(deseaseli)
patient = Patient.objects.get(user=request.user)
Search_Data.objects.create(patient=patient, prediction_accuracy=round(accuracy_score(test_Y,
final_preds)*100,2), result=predictiondata["Final Prediction"], values_list=deseaseli,
predict_for="General Health Prediction")

# print(deseaseli)
alldisease = ['Itching','Skin Rash','Nodal Skin Eruptions','Continuous
Sneezing','Shivering','Chills','Joint Pain', 'Stomach Pain','Acidity','Ulcers On Tongue','Muscle
Wasting','Vomiting','Burning Micturition','Spotting Urination','Fatigue','Weight Gain','Anxiety','Cold
Hands And Feets','Mood Swings','Weight Loss','Restlessness','Lethargy','Patches In Throat','Irregular
Sugar Level','Cough','High Fever','Sunken Eyes','Breathlessness','Sweating','Dehydration',
'Indigestion','Headache','Yellowish Skin','Dark Urine','Nausea','Loss Of Appetite','Pain Behind
The Eyes','Back Pain','Constipation','Abdominal Pain','Diarrhoea','Mild Fever','Yellow
Urine','Yellowing Of Eyes','Acute Liver Failure','Fluid Overload','Swelling Of Stomach','Swelled
Lymph Nodes','Malaise','Blurred And Distorted Vision','Phlegm','Throat Irritation','Redness Of
Eyes','Sinus Pressure','Runny Nose','Congestion','Chest Pain','Weakness In Limbs','Fast Heart Rate',
'Pain During Bowel Movements','Pain In Anal Region','Bloody Stool','Irritation In Anus','Neck
Pain','Dizziness','Cramps','Bruising','Obesity','Swollen Legs','Swollen Blood Vessels','Puffy Face And

63
Eyes','Enlarged Thyroid','Brittle Nails','Swollen Extremeties','Excessive Hunger','Extra Marital
Contacts','Drying And Tingling Lips','Slurred Speech','Knee Pain','Hip Joint Pain','Muscle
Weakness','Stiff Neck','Swelling Joints','Movement Stiffness','Spinning Movements','Loss Of
Balance','Unsteadiness','Weakness Of One Body Side','Loss Of Smell','Bladder
Discomfort','Continuous Feel Of Urine','Passage Of Gases','Internal Itching','Toxic Look (Typhos)',
'Depression','Irritability','Muscle Pain','Altered Sensorium','Red Spots Over Body','Belly
Pain','Abnormal Menstruation','Dischromic Patches','Watering From Eyes','Increased
Appetite','Polyuria','Family History','Mucoid Sputum','Rusty Sputum','Lack Of Concentration',
'Visual Disturbances','Receiving Blood Transfusion','Receiving Unsterile
Injections','Coma','Stomach Bleeding', 'Distention Of Abdomen','History Of Alcohol
Consumption','Fluid Overload','Blood In Sputum','Prominent Veins On Calf','Palpitations','Painful
Walking','Pus Filled Pimples', 'Blackheads','Scurring','Skin Peeling','Silver Like Dusting','Small Dents
In Nails','Inflammatory Nails','Blister','Red Sore Around Nose','Yellow Crust Ooze','Prognosis']
return render(request,'add_genralhealth.html', {'alldisease':alldisease,
'predictiondata':predictiondata})

def search_blood(request):
data = Blood_Donation.objects.filter(status="Approved")
if request.method == "POST":
bg = request.POST['bg']
place = request.POST['place']
user = Patient.objects.get(user=request.user)
Blood_Donation.objects.create(blood_group=bg, user=user, purpose="Request for Blood",
status="Pending", place=place)
messages.success(request, "Request Generated.")
return redirect('search_blood')
return render(request, 'search_blood.html', {'data':data})

def donate_blood(request):

64
if request.method == "POST":
bg = request.POST['bg']
place = request.POST['place']
user = Patient.objects.get(user=request.user)
data = Blood_Donation.objects.create(blood_group=bg, user=user, purpose="Blood Donor",
status="Pending", place=place)
messages.success(request, "Added Your Detail.")
return redirect('donate_blood')
return render(request, 'donate_blood.html')

def request_blood(request):
mydata = request.GET.get('action',0)
data = Blood_Donation.objects.filter(purpose="Request for Blood")
if mydata:
data = data.filter(status=mydata)
return render(request, 'request_blood.html', {'data':data})

def donator_blood(request):
mydata = request.GET.get('action',0)
data = Blood_Donation.objects.filter(purpose="Blood Donor")
if mydata:
data = data.filter(status=mydata)
return render(request, 'donator_blood.html', {'data':data})

def change_status(request,pid):
data = Blood_Donation.objects.get(id=pid)
url = request.GET.get('data')
if data.status == "Approved":
data.status = "Pending"
data.save()
else:

65
data.status = "Approved"
data.save()
return HttpResponseRedirect(url)

66
CHAPTER 5
SYSTEM IMPLEMENTATION

67
5.1 INTRODUCTION

Implementation is the stage of the project where the theoretical design is turned into a working
system. It can be considered to be the most crucial stage in achieving a successful new system gaining
the users confidence that the new system will work and will be effective and accurate. It is primarily
concerned with user training and documentation. Conversion usually takes place about the same time
the user is being trained or later. Implementation simply means convening a new system design into
operation, which is the process of converting a new revised system design into an operational one.
At this stage the main work load, the greatest upheaval and the major impact on the existing system
shifts to the user department. If the implementation is not carefully planned or controlled, it can create
chaos and confusion.
Implementation includes all those activities that take place to convert from the existing system to the
new system. The new system may be a totally new, replacing an existing manual or automated system
or it may be a modification to an existing system. Proper implementation is essential to provide a
reliable system to meet organization requirements. The process of putting the developed system in
actual use is called system implementation. This includes all those activities that take place to convert
from the old system to the new system. The system can be implemented only after through testing is
done and if it is found to be working according to the specifications. The system personnel check the
feasibility of the system. The more complex the system being implemented, the more involved will be
the system analysis and design effort required to implement the three main aspects: education and
training, system testing and changeover.
The implementation state involves the following tasks:
 Careful planning.
 Investigation of system and constraints.
 Design of methods to achieve the changeover.

Implementation Procedures

Implementation of software refers to the final installation of the package in its real environment, to the
satisfaction of the intended uses and the operation of the system. In many organizations someone who
will not be operating it, will commission the software development project. In the initial stage people
doubt about the software but we have to ensure that the resistance does not build up, as one has to
make sure that:
 The active user must be aware of the benefits of using the new system.
 Their confidence in the software is built up.

 Proper guidance is imparted to the user so that he is comfortable in using the application.
 Before going ahead and viewing the system, the user must know that for viewing the result, the
server program should be running in the server. If the server object is not up running on the
server, the actual process won’t take place

68
User Training

User training is designed to prepare the user for testing and converting the system. To achieve the
objective and benefits expected from computer based system, it is essential for the people who will be
involved to be confident of their role in the new system. As system becomes more complex, the need
for training is more important. By user training the user comes to know how to enter data, respond to
error messages, interrogate the database and call up routine that will produce reports and perform
other necessary functions.

Operational Document

After providing the necessary basic training on computer awareness the user will have to be trained on
the new application software. This will give the underlying philosophy of the use of the new system
such as the screen flow, screen design type of help on the screen, type of errors

69
5.2 CODING

Coding allows humans to communicate with these devices. Modern technology such as traffic
lights, calculators, smart TVs, and cars use internal coding systems. Since computers do not
communicate like humans, coding acts as a translator. Code converts human input into numerical
sequences that computers understand.

Coding computers means programming them. Coding, sometimes called computer programming, is
the process of how we communicate with computers. Our cell phones, laptops, and tablets need
code to work. Coding helps us communicate with our devices. Without coding, smart TVs and
traffic lights wouldn’t operate. We wouldn’t be able to find our favorite podcasts or stream a movie
on television. Why? Because they all run on code.

 Benefits of learning coding languages


 Coding jobs and careers
 How to learn to code
 How much money you can make
 Most popular coding languages

70
5.2.1 Connection code

Settings.py
"""
Django settings for HealthDesease project.

Generated by 'django-admin startproject' using Django 3.1.6.

For more information on this file, see


https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see


https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.


BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production


# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!


SECRET_KEY = '5_s&43)=k=zn)ch4gx(%zwbbj6zb$!ijbi8wk6em#spkk!yq$5'

# SECURITY WARNING: don't run with debug turned on in production!


DEBUG = True

ALLOWED_HOSTS = []

# Application definition
71
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'healthapp'
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'HealthDesease.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
72
},
]

WSGI_APPLICATION = 'HealthDesease.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}

# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]

73
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)


# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'

MEDIA_URL = '/media/'
MEDIA_ROOT = Path.joinpath(BASE_DIR,'media')

Manage.py

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys

def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HealthDesease.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
74
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)

if __name__ == '__main__':
main()

Models.py

from operator import mod


from pyexpat import model
from re import M
from django.db import models
from django.contrib.auth.models import User

# Create your models here.


DOCTOR_STATUS = ((1, 'Authorize'), (2, 'UnAuthorize'))

class Patient(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
contact = models.CharField(max_length=100, null=True)
address = models.CharField(max_length=100, null=True)
dob = models.DateField(null=True)
image = models.FileField(null=True)

def __str__(self):
return self.user.username

class Doctor(models.Model):
status = models.IntegerField(DOCTOR_STATUS, null=True)
75
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
contact = models.CharField(max_length=100, null=True)
address = models.CharField(max_length=100, null=True)
category = models.CharField(max_length=100, null=True)
doj = models.DateField(null=True)
dob = models.DateField(null=True)
image = models.FileField(null=True)

def __str__(self):
return self.user.username

class Admin_Helath_CSV(models.Model):
name = models.CharField(max_length=100, null=True)
csv_file = models.FileField(null=True, blank=True)

def __str__(self):
return self.name

class Search_Data(models.Model):
patient = models.ForeignKey(Patient, on_delete=models.CASCADE, null=True)
prediction_accuracy = models.CharField(max_length=100,null=True,blank=True)
result = models.CharField(max_length=100,null=True,blank=True)
values_list = models.CharField(max_length=100,null=True,blank=True)
predict_for = models.CharField(max_length=100,null=True,blank=True)
created = models.DateTimeField(auto_now=True,null=True)

def __str__(self):
return self.patient.user.username

class Feedback(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
messages = models.TextField(null=True)
date = models.DateField(auto_now=True)

def __str__(self):
return self.user.user.username

class GeneralHealthProblem(models.Model):
name = models.CharField(max_length=100, null=True, blank=True)

def __str__(self):
return self.name

class Blood_Donation(models.Model):
status = models.CharField(max_length=100, null=True, blank=True)
user = models.ForeignKey(Patient, on_delete=models.CASCADE, null=True, blank=True)
blood_group = models.CharField(max_length=100, null=True, blank=True)
place = models.CharField(max_length=100, null=True, blank=True)
purpose = models.CharField(max_length=100, null=True, blank=True)
created = models.DateTimeField(auto_now=True,null=True)
active = models.BooleanField(null=True, blank=True, default=False)
76
def __str__(self):
return self.user.user.username

Views.Py

from django.contrib import messages


from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
import datetime

from sklearn.ensemble import GradientBoostingClassifier

from .forms import DoctorForm


from .models import *
from django.contrib.auth import authenticate, login, logout
import numpy as np
import pandas as pd

import matplotlib.pyplot as plt


import seaborn as sns
sns.set_style('darkgrid')

from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler


from sklearn.model_selection import train_test_split

from sklearn.linear_model import LogisticRegression


from sklearn.svm import SVC
from sklearn.neural_network import MLPClassifier
from django.http import HttpResponse, HttpResponseRedirect
# Create your views here.

from pickle import encode_long


import numpy as np
import pandas as pd
from scipy.stats import mode
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.svm import SVC
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, confusion_matrix

def Home(request):
return render(request,'carousel.html')
77
def Admin_Home(request):
dis = Search_Data.objects.all()
pat = Patient.objects.all()
doc = Doctor.objects.all()
feed = Feedback.objects.all()

d = {'dis':dis.count(),'pat':pat.count(),'doc':doc.count(),'feed':feed.count()}
return render(request,'admin_home.html',d)

@login_required(login_url="login")
def assign_status(request,pid):
doctor = Doctor.objects.get(id=pid)
if doctor.status == 1:
doctor.status = 2
messages.success(request, 'Selected doctor are successfully withdraw his approval.')
else:
doctor.status = 1
messages.success(request, 'Selected doctor are successfully approved.')
doctor.save()
return redirect('view_doctor')

@login_required(login_url="login")
def User_Home(request):
return render(request,'patient_home.html')

@login_required(login_url="login")
def Doctor_Home(request):
return render(request,'doctor_home.html')

def About(request):
return render(request,'about.html')

def Contact(request):
return render(request,'contact.html')

def Gallery(request):
return render(request,'gallery.html')

def Login_User(request):
error = ""
if request.method == "POST":
u = request.POST['uname']
p = request.POST['pwd']
user = authenticate(username=u, password=p)
sign = ""
if user:
try:
sign = Patient.objects.get(user=user)
78
except:
pass
if sign:
login(request, user)
error = "pat1"
else:
pure=False
try:
pure = Doctor.objects.get(status=1,user=user)
except:
pass
if pure:
login(request, user)
error = "pat2"
else:
login(request, user)
error="notmember"
else:
error="not"
d = {'error': error}
return render(request, 'login.html', d)

def Login_admin(request):
error = ""
if request.method == "POST":
u = request.POST['uname']
p = request.POST['pwd']
user = authenticate(username=u, password=p)
if user.is_staff:
login(request, user)
error="pat"
else:
error="not"
d = {'error': error}
return render(request, 'admin_login.html', d)

def Signup_User(request):
error = ""
if request.method == 'POST':
f = request.POST['fname']
l = request.POST['lname']
u = request.POST['uname']
e = request.POST['email']
p = request.POST['pwd']
d = request.POST['dob']
con = request.POST['contact']
add = request.POST['add']
type = request.POST['type']
im = request.FILES['image']
dat = datetime.date.today()
user = User.objects.create_user(email=e, username=u, password=p, first_name=f,last_name=l)
79
if type == "Patient":
Patient.objects.create(user=user,contact=con,address=add,image=im,dob=d)
else:
Doctor.objects.create(dob=d,image=im,user=user,contact=con,address=add,status=2)
error = "create"
d = {'error':error}
return render(request,'register.html',d)

def Logout(request):
logout(request)
return redirect('home')

@login_required(login_url="login")
def Change_Password(request):
sign = 0
user = User.objects.get(username=request.user.username)
error = ""
if not request.user.is_staff:
try:
sign = Patient.objects.get(user=user)
if sign:
error = "pat"
except:
sign = Doctor.objects.get(user=user)
terror = ""
if request.method=="POST":
n = request.POST['pwd1']
c = request.POST['pwd2']
o = request.POST['pwd3']
if c == n:
u = User.objects.get(username__exact=request.user.username)
u.set_password(n)
u.save()
terror = "yes"
else:
terror = "not"
d = {'error':error,'terror':terror,'data':sign}
return render(request,'change_password.html',d)

def preprocess_inputs(df, scaler):


df = df.copy()
# Split df into X and y
y = df['target'].copy()
X = df.drop('target', axis=1).copy()
X = pd.DataFrame(scaler.fit_transform(X), columns=X.columns)
return X, y

def prdict_heart_disease(list_data):
csv_file = Admin_Helath_CSV.objects.get(id=1)
80
df = pd.read_csv(csv_file.csv_file)

X = df[['age','sex','cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thalach', 'exang', 'oldpeak', 'slope', 'ca',
'thal']]
y = df['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8, random_state=0)
nn_model = GradientBoostingClassifier(n_estimators=100,learning_rate=1.0,max_depth=1,
random_state=0)
nn_model.fit(X_train, y_train)
pred = nn_model.predict([list_data])
print("Neural Network Accuracy: {:.2f}%".format(nn_model.score(X_test, y_test) * 100))
print("Prdicted Value is : ", format(pred))
dataframe = str(df.head())
return (nn_model.score(X_test, y_test) * 100),(pred)

@login_required(login_url="login")
def add_doctor(request,pid=None):
doctor = None
if pid:
doctor = Doctor.objects.get(id=pid)
if request.method == "POST":
form = DoctorForm(request.POST, request.FILES, instance = doctor)
if form.is_valid():
new_doc = form.save()
new_doc.status = 1
if not pid:
user = User.objects.create_user(password=request.POST['password'],
username=request.POST['username'], first_name=request.POST['first_name'],
last_name=request.POST['last_name'])
new_doc.user = user
new_doc.save()
return redirect('view_doctor')
d = {"doctor": doctor}
return render(request, 'add_doctor.html', d)

@login_required(login_url="login")
def add_heartdetail(request):
if request.method == "POST":
# list_data = [57, 0, 1, 130, 236, 0, 0, 174, 0, 0.0, 1, 1, 2]
list_data = []
value_dict = eval(str(request.POST)[12:-1])
count = 0
for key,value in value_dict.items():
if count == 0:
count =1
continue
if key == "sex" and value[0] == "Male" or value[0] == 'male' or value[0]=='m' or value[0] == 'M':
list_data.append(0)
continue
elif key == "sex":
list_data.append(1)
81
continue
list_data.append(value[0])

# list_data = [57, 0, 1, 130, 236, 0, 0, 174, 0, 0.0, 1, 1, 2]


accuracy,pred = prdict_heart_disease(list_data)
patient = Patient.objects.get(user=request.user)
Search_Data.objects.create(patient=patient, prediction_accuracy=round(accuracy,2),
result=pred[0], values_list=list_data,predict_for="Heart Prediction")
rem = int(pred[0])
print("Result = ",rem)
if pred[0] == 0:
pred = "<span style='color:green'>You are healthy</span>"
else:
pred = "<span style='color:red'>You are Unhealthy, Need to Checkup.</span>"
return redirect('predict_desease', str(rem), str(round(accuracy,2)))
return render(request, 'add_heartdetail.html')

@login_required(login_url="login")
def predict_desease(request, pred, accuracy):
doctor = Doctor.objects.filter(address__icontains=Patient.objects.get(user=request.user).address)
d = {'pred': pred, 'accuracy':accuracy, 'doctor':doctor}
return render(request, 'predict_disease.html', d)

@login_required(login_url="login")
def view_search_pat(request):
doc = None
try:
doc = Doctor.objects.get(user=request.user)
data = Search_Data.objects.filter(patient__address__icontains=doc.address).order_by('-id')
except:
try:
doc = Patient.objects.get(user=request.user)
data = Search_Data.objects.filter(patient=doc).order_by('-id')
except:
data = Search_Data.objects.all().order_by('-id')
return render(request,'view_search_pat.html',{'data':data})

@login_required(login_url="login")
def delete_doctor(request,pid):
doc = Doctor.objects.get(id=pid)
doc.delete()
return redirect('view_doctor')

@login_required(login_url="login")
def delete_feedback(request,pid):
doc = Feedback.objects.get(id=pid)
doc.delete()
return redirect('view_feedback')

@login_required(login_url="login")
def delete_patient(request,pid):
82
doc = Patient.objects.get(id=pid)
doc.delete()
return redirect('view_patient')

@login_required(login_url="login")
def delete_searched(request,pid):
doc = Search_Data.objects.get(id=pid)
doc.delete()
return redirect('view_search_pat')

@login_required(login_url="login")
def View_Doctor(request):
doc = Doctor.objects.all()
d = {'doc':doc}
return render(request,'view_doctor.html',d)

@login_required(login_url="login")
def View_Patient(request):
patient = Patient.objects.all()
d = {'patient':patient}
return render(request,'view_patient.html',d)

@login_required(login_url="login")
def View_Feedback(request):
dis = Feedback.objects.all()
d = {'dis':dis}
return render(request,'view_feedback.html',d)

@login_required(login_url="login")
def View_My_Detail(request):
terror = ""
user = User.objects.get(id=request.user.id)
error = ""
try:
sign = Patient.objects.get(user=user)
error = "pat"
except:
sign = Doctor.objects.get(user=user)
d = {'error': error,'pro':sign}
return render(request,'profile_doctor.html',d)

@login_required(login_url="login")
def Edit_Doctor(request,pid):
doc = Doctor.objects.get(id=pid)
error = ""
# type = Type.objects.all()
if request.method == 'POST':
f = request.POST['fname']
l = request.POST['lname']
e = request.POST['email']
con = request.POST['contact']
83
add = request.POST['add']
cat = request.POST['type']
try:
im = request.FILES['image']
doc.image=im
doc.save()
except:
pass
dat = datetime.date.today()
doc.user.first_name = f
doc.user.last_name = l
doc.user.email = e
doc.contact = con
doc.category = cat
doc.address = add
doc.user.save()
doc.save()
error = "create"
d = {'error':error,'doc':doc,'type':type}
return render(request,'edit_doctor.html',d)

@login_required(login_url="login")
def Edit_My_deatail(request):
terror = ""
print("Hii welvome")
user = User.objects.get(id=request.user.id)
error = ""
# type = Type.objects.all()
try:
sign = Patient.objects.get(user=user)
error = "pat"
except:
sign = Doctor.objects.get(user=user)
if request.method == 'POST':
f = request.POST['fname']
l = request.POST['lname']
e = request.POST['email']
con = request.POST['contact']
add = request.POST['add']
try:
im = request.FILES['image']
sign.image = im
sign.save()
except:
pass
to1 = datetime.date.today()
sign.user.first_name = f
sign.user.last_name = l
sign.user.email = e
sign.contact = con
if error != "pat":
84
cat = request.POST['type']
sign.category = cat
sign.save()
sign.address = add
sign.user.save()
sign.save()
terror = "create"
d = {'error':error,'terror':terror,'doc':sign}
return render(request,'edit_profile.html',d)

@login_required(login_url='login')
def sent_feedback(request):
terror = None
if request.method == "POST":
username = request.POST['uname']
message = request.POST['msg']
username = User.objects.get(username=username)
Feedback.objects.create(user=username, messages=message)
terror = "create"
return render(request, 'sent_feedback.html',{'terror':terror})

def add_genralhealth(request):
predictiondata = None
deseaseli = []
if request.method=="POST":
for i,j in request.POST.items():
if "csrfmiddlewaretoken" != i:
deseaseli.append(i)
# training.csv
DATA_PATH = Admin_Helath_CSV.objects.get(id=2)
#df = pd.read_csv(csv_file.csv_file)
#DATA_PATH = "c:/Users/bhuwa/OneDrive/Desktop/dataset/Training.csv"
data = pd.read_csv(DATA_PATH.csv_file).dropna(axis = 1)

# Checking whether the dataset is balanced or not


disease_counts = data["prognosis"].value_counts()
temp_df = pd.DataFrame({
"Disease": disease_counts.index,
"Counts": disease_counts.values
})

plt.figure(figsize = (18,8))
sns.barplot(x = "Disease", y = "Counts", data = temp_df)
plt.xticks(rotation=90)
# plt.show()

# Encoding the target value into numerical


# value using LabelEncoder
encoder = LabelEncoder()
data["prognosis"] = encoder.fit_transform(data["prognosis"])
85
X = data.iloc[:,:-1]
y = data.iloc[:, -1]
X_train, X_test, y_train, y_test =train_test_split(
X, y, test_size = 0.2, random_state = 24)

symptoms = X.columns.values
symptom_index = {}
for index, value in enumerate(symptoms):
symptom = " ".join([i.capitalize() for i in value.split("_")])
symptom_index[symptom] = index

data_dict = {
"symptom_index":symptom_index,
"predictions_classes":encoder.classes_
}

final_svm_model = SVC()
final_nb_model = GaussianNB()
final_rf_model = RandomForestClassifier(random_state=18)
final_svm_model.fit(X, y)
final_nb_model.fit(X, y)
final_rf_model.fit(X, y)

#Testing.csv
DATA_PATH2 = Admin_Helath_CSV.objects.get(id=3)
test_data = pd.read_csv(DATA_PATH2.csv_file).dropna(axis=1)

test_X = test_data.iloc[:, :-1]


test_Y = encoder.transform(test_data.iloc[:, -1])

svm_preds = final_svm_model.predict(test_X)
nb_preds = final_nb_model.predict(test_X)
rf_preds = final_rf_model.predict(test_X)

final_preds = [mode([i,j,k])[0][0] for i,j,


k in zip(svm_preds, nb_preds, rf_preds)]

print(f"Accuracy on Test dataset by the combined model\


: {accuracy_score(test_Y, final_preds)*100}")

cf_matrix = confusion_matrix(test_Y, final_preds)


plt.figure(figsize=(12,8))

sns.heatmap(cf_matrix, annot = True)


# plt.title("Confusion Matrix for Combined Model on Test Dataset")
# # plt.show()

86
def predictDisease(symptoms):
# print("All Symptoms = ", symptoms)
# symptoms = symptoms.split(",")

# # creating input data for the models


input_data = [0] * len(data_dict["symptom_index"])
for symptom in symptoms:
index = data_dict["symptom_index"][symptom]
input_data[index] = 1

# reshaping the input data and converting it


# into suitable format for model predictions
input_data = np.array(input_data).reshape(1,-1)

# generating individual outputs


rf_prediction = data_dict["predictions_classes"][final_rf_model.predict(input_data)[0]]
nb_prediction = data_dict["predictions_classes"][final_nb_model.predict(input_data)[0]]
svm_prediction = data_dict["predictions_classes"][final_svm_model.predict(input_data)[0]]

# making final prediction by taking mode of all predictions


final_prediction = mode([rf_prediction, nb_prediction, svm_prediction])[0][0]
predictions = {
"RandomForestClassifier Prediction": rf_prediction,
"GaussianNB Prediction": nb_prediction,
"SVC Prediction": svm_prediction,
"Final Prediction":final_prediction
}
return predictions

# Testing the function


predictiondata = predictDisease(deseaseli)
patient = Patient.objects.get(user=request.user)
Search_Data.objects.create(patient=patient, prediction_accuracy=round(accuracy_score(test_Y,
final_preds)*100,2), result=predictiondata["Final Prediction"], values_list=deseaseli,
predict_for="General Health Prediction")

# print(deseaseli)
alldisease = ['Itching','Skin Rash','Nodal Skin Eruptions','Continuous
Sneezing','Shivering','Chills','Joint Pain', 'Stomach Pain','Acidity','Ulcers On Tongue','Muscle
Wasting','Vomiting','Burning Micturition','Spotting Urination','Fatigue','Weight Gain','Anxiety','Cold
Hands And Feets','Mood Swings','Weight Loss','Restlessness','Lethargy','Patches In Throat','Irregular
Sugar Level','Cough','High Fever','Sunken Eyes','Breathlessness','Sweating','Dehydration',
'Indigestion','Headache','Yellowish Skin','Dark Urine','Nausea','Loss Of Appetite','Pain Behind
The Eyes','Back Pain','Constipation','Abdominal Pain','Diarrhoea','Mild Fever','Yellow
Urine','Yellowing Of Eyes','Acute Liver Failure','Fluid Overload','Swelling Of Stomach','Swelled
Lymph Nodes','Malaise','Blurred And Distorted Vision','Phlegm','Throat Irritation','Redness Of
Eyes','Sinus Pressure','Runny Nose','Congestion','Chest Pain','Weakness In Limbs','Fast Heart Rate',
'Pain During Bowel Movements','Pain In Anal Region','Bloody Stool','Irritation In Anus','Neck
Pain','Dizziness','Cramps','Bruising','Obesity','Swollen Legs','Swollen Blood Vessels','Puffy Face And
Eyes','Enlarged Thyroid','Brittle Nails','Swollen Extremeties','Excessive Hunger','Extra Marital
Contacts','Drying And Tingling Lips','Slurred Speech','Knee Pain','Hip Joint Pain','Muscle
87
Weakness','Stiff Neck','Swelling Joints','Movement Stiffness','Spinning Movements','Loss Of
Balance','Unsteadiness','Weakness Of One Body Side','Loss Of Smell','Bladder Discomfort','Continuous
Feel Of Urine','Passage Of Gases','Internal Itching','Toxic Look (Typhos)',
'Depression','Irritability','Muscle Pain','Altered Sensorium','Red Spots Over Body','Belly
Pain','Abnormal Menstruation','Dischromic Patches','Watering From Eyes','Increased
Appetite','Polyuria','Family History','Mucoid Sputum','Rusty Sputum','Lack Of Concentration',
'Visual Disturbances','Receiving Blood Transfusion','Receiving Unsterile
Injections','Coma','Stomach Bleeding', 'Distention Of Abdomen','History Of Alcohol
Consumption','Fluid Overload','Blood In Sputum','Prominent Veins On Calf','Palpitations','Painful
Walking','Pus Filled Pimples', 'Blackheads','Scurring','Skin Peeling','Silver Like Dusting','Small Dents
In Nails','Inflammatory Nails','Blister','Red Sore Around Nose','Yellow Crust Ooze','Prognosis']
return render(request,'add_genralhealth.html', {'alldisease':alldisease,
'predictiondata':predictiondata})

def search_blood(request):
data = Blood_Donation.objects.filter(status="Approved")
if request.method == "POST":
bg = request.POST['bg']
place = request.POST['place']
user = Patient.objects.get(user=request.user)
Blood_Donation.objects.create(blood_group=bg, user=user, purpose="Request for Blood",
status="Pending", place=place)
messages.success(request, "Request Generated.")
return redirect('search_blood')
return render(request, 'search_blood.html', {'data':data})

def donate_blood(request):
if request.method == "POST":
bg = request.POST['bg']
place = request.POST['place']
user = Patient.objects.get(user=request.user)
data = Blood_Donation.objects.create(blood_group=bg, user=user, purpose="Blood Donor",
status="Pending", place=place)
messages.success(request, "Added Your Detail.")
return redirect('donate_blood')
return render(request, 'donate_blood.html')

def request_blood(request):
mydata = request.GET.get('action',0)
data = Blood_Donation.objects.filter(purpose="Request for Blood")
if mydata:
data = data.filter(status=mydata)
return render(request, 'request_blood.html', {'data':data})

def donator_blood(request):
mydata = request.GET.get('action',0)
data = Blood_Donation.objects.filter(purpose="Blood Donor")
if mydata:
data = data.filter(status=mydata)
88
return render(request, 'donator_blood.html', {'data':data})

def change_status(request,pid):
data = Blood_Donation.objects.get(id=pid)
url = request.GET.get('data')
if data.status == "Approved":
data.status = "Pending"
data.save()
else:
data.status = "Approved"
data.save()
return HttpResponseRedirect(url)

Urls.py

"""HealthDesease URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from healthapp.views import *
# from .api import router

urlpatterns = [
# path('api/sensoviz/', include(router.urls)),
path('admin/', admin.site.urls),
path('', Home, name="home"),
path('patient_home', User_Home,name="patient_home"),
path('doctor_home', Doctor_Home,name="doctor_home"),
path('admin_home', Admin_Home,name="admin_home"),
path('about', About,name="about"),
path('contact', Contact,name="contact"),
path('gallery', Gallery,name="gallery"),
path('login', Login_User,name="login"),
path('login_admin', Login_admin,name="login_admin"),
path('signup', Signup_User,name="signup"),
89
path('logout', Logout,name="logout"),
path('change_password', Change_Password,name="change_password"),
# path('prdict_heart_disease', prdict_heart_disease,name="prdict_heart_disease"),
path('add_heartdetail', add_heartdetail,name="add_heartdetail"),
path('view_search_pat', view_search_pat,name="view_search_pat"),

path('view_doctor', View_Doctor,name="view_doctor"),
path('add_doctor', add_doctor,name="add_doctor"),
path('change_doctor/<int:pid>/', add_doctor,name="change_doctor"),
path('view_patient', View_Patient,name="view_patient"),
path('view_feedback', View_Feedback,name="view_feedback"),
path('edit_profile', Edit_My_deatail,name="edit_profile"),
path('profile_doctor', View_My_Detail,name="profile_doctor"),
path('sent_feedback', sent_feedback,name="sent_feedback"),

path('delete_searched/<int:pid>', delete_searched, name="delete_searched"),


path('delete_doctor<int:pid>', delete_doctor, name="delete_doctor"),
path('assign_status<int:pid>', assign_status, name="assign_status"),
path('delete_patient<int:pid>', delete_patient, name="delete_patient"),
path('delete_feedback<int:pid>', delete_feedback, name="delete_feedback"),
path('predict_desease/<str:pred>/<str:accuracy>/', predict_desease, name="predict_desease"),

path('add_genralhealth', add_genralhealth, name="add_genralhealth"),

path('search_blood', search_blood, name="search_blood"),


path('donate_blood', donate_blood, name="donate_blood"),

path('request_blood', request_blood, name="request_blood"),


path('donator_blood', donator_blood, name="donator_blood"),

path('change_status/<int:pid>/', change_status, name="change_status")

]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

90
5.3 Unit Testing

Unit testing focuses verification effort on the smallest unit of software design – the software
component or module. Using the component level design description as a guide, important
control paths are tested to uncover errors within the boundary of the module. The relative
complexity of tests and uncovered scope established for unit testing. The unit testing is white-
box oriented, and step can be conducted in parallel for multiple components. The modular
interface is tested to ensure that information properly flows into and out of the program unit
under test. The local data structure is examined to ensure that data stored temporarily maintains
its integrity during all steps in an algorithm’s execution. Boundary conditions are tested to ensure
that all statements in a module have been executed at least once. Finally, all error handling paths
are tested.

Tests of data flow across a module interface are required before any other test is initiated. If data
do not enter and exit properly, all other tests are moot. Selective testing of execution paths is an
essential task during the unit test. Good design dictates that error conditions be anticipated and
error handling paths set up to reroute or cleanly terminate processing when an error does occur.
Boundary testing is the last task of unit testing step. Software often fails at its boundaries.

5.3.1 Test Plan & Test Case

A test plan implies a series of desired course of action to be followed in accomplishing various
testing methods. The Test Plan acts as a blue print for the action that is to be followed. The
software engineers create a computer program, its documentation and related data structures. The
software developers is always responsible for testing the individual units of the programs, ensuring
that each performs the function for which it was designed. There is an independent test group
(ITG) which is to remove the inherent problems associated with letting the builder to test.

91
CHAPTER 6

SYSTEM TESTING

92
6.1 INTRODUCTION
Software Testing is the process of executing software in a controlled manner, in order to answer the
question - Does the software behave as specified? Software testing is often used in association with
the terms verification and validation. Validation is the checking or testing of items, includes
software, for conformance and consistency with an associated specification. Software testing is just
one kind of verification, which also uses techniques such as reviews, analysis, inspections, and
walkthroughs. Validation is the process of checking that what has been specified is what the user
actually wanted.

Other activities which are often associated with software testing are static analysis and dynamic
analysis. Static analysis investigates the source code of software, looking for problems and
gathering metrics without actually executing the code. Dynamic analysis looks at the behavior of
software while it is executing, to provide information such as execution traces, timing profiles, and
test coverage information.

Testing is a set of activity that can be planned in advanced and conducted systematically. Testing
begins at the module level and work towards the integration of entire computers based system.
Nothing is complete without testing, as it vital success of the system testing objectives, there are
several rules that can serve as testing objectives. They are:

Testing is a process of executing a program with the intent of finding an error.

 A good test case is one that has high possibility of finding an undiscovered error.
 A successful test is one that uncovers an undiscovered error.

If a testing is conducted successfully according to the objectives as stated above, it would uncover
errors in the software. Also testing demonstrate that the software function appear to be working
according to the specification, that performance requirement appear to have been met.

There are three ways to test program.

 For correctness
 For implementation efficiency
 For computational complexity

Test Plan & Test Case

A test plan implies a series of desired course of action to be followed in accomplishing various
testing methods. The Test Plan acts as a blue print for the action that is to be followed. The
software engineers create a computer program, its documentation and related data structures. The
software developers is always responsible for testing the individual units of the programs, ensuring
93
that each performs the function for which it was designed. There is an independent test group
(ITG) which is to remove the inherent problems associated with letting the builder to test.

94
the thing that has been built. The specific objectives of testing should be stated in measurable
terms. So that the mean time to failure, the cost to find and fix the defects, remaining defect
density or frequency of occurrence and test work-hours per regression test all should be stated
within the test plan.

The levels of testing include:

 Unit testing
 Integration Testing
 Validation Testing
 Output Testing

6.1.1 Integration Testing

Integration testing is systematic technique for constructing the program structure while at the
same time conducting tests to uncover errors associated with interfacing. The objective is to take
unit tested components and build a program structure that has been dictated by design. The entire
program is tested as whole. Correction is difficult because isolation of causes is complicated by
vast expanse of entire program. Once these errors are corrected, new ones appear and the process
continues in a seemingly endless loop. After performing unit testing in the System all the
modules were integrated to test for any inconsistencies in the interfaces. Moreover differences in
program structures were removed and a unique program structure was evolved.

6.1.2 Validation Testing or System Testing

This is the final step in testing. In this the entire system was tested as a whole with all forms,
code, modules and class modules. This form of testing is popularly known as Black Box testing
or System tests.

Black Box testing method focuses on the functional requirements of the software. That is, Black
Box testing enables the software engineer to derive sets of input conditions that will fully
exercise all functional requirements for a program.

Black Box testing attempts to find errors in the following categories; incorrect or missing
functions, interface errors, errors in data structures or external data access, performance errors
and initialization errors and termination errors.

6.1.3 Acceptance Testing

The system considered is tested for user acceptance; here it should satisfy the firm’s need. The
software should keep in touch with perspective system; user at the time of developing and
making changes whenever required. This done with respect to the following points:

95
 Input Screen Designs
 Output Screen Designs

The above testing is done taking various kinds of test data. Preparation of test data plays a vital
role in the system testing. After preparing the test data, the system under study is tested using
that test data. While testing the system by which test data errors are again uncovered and
corrected by using above testing steps and corrections are also noted for future use.

96
CHAPTER 7
SYSTEM MAINTENANCE

97
7.1 INTRODUCTION

During the maintenance stage of the SDLC (System Development Lifecycle), the system is assessed to
ensure it does not become obsolete. This is also where changes are made to initial software. It involves
continuous evaluation of the system in terms of its performance.

7.2 MAINTENANCE

System maintenance is an ongoing activity, which covers a wide variety of activities, including
removing program and design errors, updating documentation and test data and updating user support.
Maintenance may incurred for:
• Hosting
• Domain name
• New Feature Update
• Hardware upgradation
• License policy change

98
CHAPTER 8
SYSTEM SECURITY MEASURES

99
8. SYSTEM SECURITY

8.1 IMPLEMENTATION OF SECURITY

Security mechanism comes at two levels: one at the operation system level and other at
the database level. The operating system level security is implemented at several levels, ranging
from passwords to access to the system to the isolation of concurrent process run within the
system. The os defines access to the system if the password and username is invalid. Internet
security is catching all term for a very broad issue covering security for transactions made over
the internet. Generally, internet security encompasses browser security, the security of data
entered through a web form and overall authentication and protection of data send via internet
protocol.

Online system is just as secure. Most online canteen automation system programs
allow you to create multiple user accounts with various level of access. Your data is stored on
secure, protected servers that feature firewalls and other online security programs

8.2 DATABASE SECURITY

Database security refers to the collective measures used to protect and secure a database or
DBMS from intimate use and malicious threats and attacks. Database security covers and
enforces security on all aspects and components of databases. Database security ids generally
planned. Implemented and maintained by a database administrator and or any other information
security professional.

System, function, and data access controls, along with the associated user identification,
authentication and rights management functions, have

always been important to limit and in some cases log the activities of authorized users and
administrators.

100
CHAPTER 9
SYSTEM PLANING & SCHEDULING

101
9.1 INTRODUCTION

Planning is very important in every aspect of development work. Good managers carefully monitor
developments at various phases. Improper planning leads to failure of the project. Software project
pan can be viewed as the following:

1. within the organization: How the project is to be implemented? What are various constraints? What
is market strategy?
2. With respect to the customer: Weekly or timely meetings with the customer with presentations on
status reports. Customer feedback is also taken and further modifications and developments are done.
Project milestones and deliverables are also presented to the customer.

9.2 STEPS INVOLVED IN PLANNING A SYSTEM

Selection of project: Includes identifying project’s aims and objectives, understanding requirements
and specification, methods of analysis, design and implementation, testing techniques and
documentation.

1. Project milestones and deliverables


2. Project estimates: including cost, time, size of code and duration
3. Resource allocation: including hardware, software, previous relevant project information and digital
library
4. Risk management: including risk avoidance, risk detection, risk control and risk recovery
5. Scheduling techniques: including work breakdown structure, activity graph, critical path method
Gantt chart and Program Evaluation Review Technique.
6. People: including staff recruitment, team management and customer interaction.
7. Quality control and standard Project planning is part of project management, which relates to the
use of schedules such as Gantt charts to plan and subsequently report progress within the project
environment.

102
103
CHAPTER 10
SYSTEM COST ESTIMATION

104
10.1 INTRODUCTION

Cost estimation simply means a technique that is used to find out the cost estimates. The cost estimate
is the financial spend that is done on the efforts to develop and test software in Software Engineering.
Cost estimation models are some mathematical algorithms or parametric equations that are used to
estimate the cost of a product or a project.

• During the planning stage, one needs to choose how many engineers are required for the project and
to develop a schedule.
• In monitoring the project's progress, one needs to access whether the project is progressing according
to the procedure and takes corrective action, if necessary.

10.2 LOC BASED ESTIMATION

As Lines of Code (LOC) only counts the volume of code, you can only use it to compare or estimate
projects that use the same language and are coded using the same coding standards. Features:
Variations such as “source lines of code”, are used to set out a code base. LOC is frequently used in
some kinds of arguments.
LOC - Total number of lines in the file. LOC Changed - Total number of added + removed + modified
lines. LOC Added - Lines added. LOC Removed - Lines deleted.

105
CHAPTER 11
FUTURE ENHANCEMENT AND SCOPE OF
FURTHER DEVELOPMENT

106
11.1 INTRODUCTION

Enhancements are the perquisite for development of a system. Every existing system has proposed
enhancements which make it better and to be used more secure. The enhancements that have been
proposed for this system are listed here. Changes can occur at anytime, anywhere. As the saying goes
“Change is the only thing that is certain”. The needs can be vary day by day. Especially in business, to
complete with competitors, the firm must cope up with the advancement of technologies. It is
necessary to make provision for the same. The application developed can be done with the capability
for easy integration with other system. New modules can be added to the existing system with less
effort. Introducing the distributed database concept can make further extension to this system. Making
enhancements is all about perfective maintenance. It means adding, modifying or redeveloping the
code to support changes in the specifications. It is necessary to keep up with changing user needs and
the operational environment. More money and time is spent on perfective maintenance than on
corrective or adaptive maintenance together. Here all the facilities are made and tested. In near future
it will be extended in wide range. The new ideas are following,

 Customers can track there servicing stages of mobile phones/other devices.


 Developing a mobile application is more useful for tracking the stages of servicing.
 Allows online payments.

11.2 MERITS OF PROPOSED SYSTEM


The system is very simple in design and to implement. The system requires very low system resources
and the system will work in almost all configurations. It has got following features

Save time of customers in quickly reserving all the facility of resort

The ability to book room any time, from anywhere with internet access.

Provide the information about resort facilities.

User friendly

107
 Better security: -
For data to remain secure measures must be taken to prevent unauthorized access. Security means that
data are protected from various forms of destruction. The system security problem can be divided into
four related issues: security, integrity, privacy and confidentiality. Username and password
requirement to sign in ensures security. It will also provide data security as we are using the secured
databases for maintaining the documents.
 Ensure data accuracy: -
The proposed system eliminates the manual errors while entering the details of the users during
the registration.

 Better service: -
The product will avoid the burden of hard copy storage. We can also conserve the time and
human resources for doing the same task. The data can be maintained for longer period
with no loss of data.

User friendliness and interactive: -


The proposed system’s interface help the users to perform their operations without any
confusions or difficulties. A customer can easily find their interested products and can able
to purchase it.

108
109
CHAPTER 12

CONCLUSION

110
CONCLUSION
It has been a great pleasure for me to work on this exciting and challenging project. This project
proved good for me as it provided practical knowledge of not only programming in Python and Sqlite
web based application. It also provides knowledge about the latest technology used in developing web
enabled application and client server technology that will be great demand in future. This will provide
better opportunities and guidance in future in developing projects independently.

111
ANNEXURE

112
ORGANIZATION PROFILE

Networkz Systems- a division of Trinetz Technology private limited is an IT/ITes skill training
company headquartered in kerala. Networkzsystems is an approved training and testing centre of
National Skill India Mission ( NSIM ). We promote courses from emerging technologies like Network
Engineering, Machine learning, Data science, Artificial intelligence, full stack development, Cyber
security, Ethical hacking and much more . we have the right team, tool and technology to handle any
kind of advanced IT training.Networkz systems act as a technology training partner for many
institutions and corporates. we enhance employment prospects of students by providing employability
skills in IT/ITes industry. The training modules and curriculum is prepared after consultation with
industry experts and companies. The technical trainers are qualified and trained by industry experts on
latest technology. Our product & curriculum development team ensures that the latest technology is
delivered to our students .

113
6. REFERENCES
Books/References:

 Gary B. Shelly, Harry J. Rosenblatt, “System Analysis and Design”, 2009.

 Roger S Pressman, “Software Engineering”, 1994.

 PankajJalote, “Software engineering: a precise approach”, 2006.

 James lee and Brent ware Addison, “Open source web development with LAMP”, 2003

 IEEE Std 1016 Recommended Practice for Software Design Descriptions.

Websites:

 www.w3schools.com

 www.jquery.com

 http://homepages.dcc.ufmg.br/~rodolfo/es-1-03/IEEE-Std-830-1998.pdf

www.agilemodeling.com/artifacts/useCaseDiagram.html

114
Connection code
Settings.py
"""
Django settings for HealthDesease project.

Generated by 'django-admin startproject' using Django 3.1.6.

For more information on this file, see


https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see


https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.


BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production


# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!


SECRET_KEY = '5_s&43)=k=zn)ch4gx(%zwbbj6zb$!ijbi8wk6em#spkk!yq$5'

# SECURITY WARNING: don't run with debug turned on in production!


DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [

115
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'healthapp'
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'HealthDesease.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
116
WSGI_APPLICATION = 'HealthDesease.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}

# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]

# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
117
LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)


# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'

MEDIA_URL = '/media/'
MEDIA_ROOT = Path.joinpath(BASE_DIR,'media')

Manage.py

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys

def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HealthDesease.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
118
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)

if __name__ == '__main__':
main()

Models.py

from operator import mod


from pyexpat import model
from re import M
from django.db import models
from django.contrib.auth.models import User

# Create your models here.


DOCTOR_STATUS = ((1, 'Authorize'), (2, 'UnAuthorize'))

class Patient(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
contact = models.CharField(max_length=100, null=True)
address = models.CharField(max_length=100, null=True)
dob = models.DateField(null=True)
image = models.FileField(null=True)

def __str__(self):
return self.user.username

class Doctor(models.Model):
status = models.IntegerField(DOCTOR_STATUS, null=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
contact = models.CharField(max_length=100, null=True)
address = models.CharField(max_length=100, null=True)
category = models.CharField(max_length=100, null=True)
doj = models.DateField(null=True)
dob = models.DateField(null=True)
image = models.FileField(null=True)

def __str__(self):
return self.user.username

class Admin_Helath_CSV(models.Model):

119
name = models.CharField(max_length=100, null=True)
csv_file = models.FileField(null=True, blank=True)

def __str__(self):
return self.name

class Search_Data(models.Model):
patient = models.ForeignKey(Patient, on_delete=models.CASCADE, null=True)
prediction_accuracy = models.CharField(max_length=100,null=True,blank=True)
result = models.CharField(max_length=100,null=True,blank=True)
values_list = models.CharField(max_length=100,null=True,blank=True)
predict_for = models.CharField(max_length=100,null=True,blank=True)
created = models.DateTimeField(auto_now=True,null=True)

def __str__(self):
return self.patient.user.username

class Feedback(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
messages = models.TextField(null=True)
date = models.DateField(auto_now=True)

def __str__(self):
return self.user.user.username

class GeneralHealthProblem(models.Model):
name = models.CharField(max_length=100, null=True, blank=True)

def __str__(self):
return self.name

class Blood_Donation(models.Model):
status = models.CharField(max_length=100, null=True, blank=True)
user = models.ForeignKey(Patient, on_delete=models.CASCADE, null=True, blank=True)
blood_group = models.CharField(max_length=100, null=True, blank=True)
place = models.CharField(max_length=100, null=True, blank=True)
purpose = models.CharField(max_length=100, null=True, blank=True)
created = models.DateTimeField(auto_now=True,null=True)
active = models.BooleanField(null=True, blank=True, default=False)

def __str__(self):
return self.user.user.username

Views.Py

from django.contrib import messages


from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
import datetime
120
from sklearn.ensemble import GradientBoostingClassifier

from .forms import DoctorForm


from .models import *
from django.contrib.auth import authenticate, login, logout
import numpy as np
import pandas as pd

import matplotlib.pyplot as plt


import seaborn as sns
sns.set_style('darkgrid')

from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler


from sklearn.model_selection import train_test_split

from sklearn.linear_model import LogisticRegression


from sklearn.svm import SVC
from sklearn.neural_network import MLPClassifier
from django.http import HttpResponse, HttpResponseRedirect
# Create your views here.

from pickle import encode_long


import numpy as np
import pandas as pd
from scipy.stats import mode
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.svm import SVC
from sklearn.naive_bayes import GaussianNB
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, confusion_matrix

def Home(request):
return render(request,'carousel.html')

def Admin_Home(request):
dis = Search_Data.objects.all()
pat = Patient.objects.all()
doc = Doctor.objects.all()
feed = Feedback.objects.all()

d = {'dis':dis.count(),'pat':pat.count(),'doc':doc.count(),'feed':feed.count()}
return render(request,'admin_home.html',d)

@login_required(login_url="login")
def assign_status(request,pid):
121
doctor = Doctor.objects.get(id=pid)
if doctor.status == 1:
doctor.status = 2
messages.success(request, 'Selected doctor are successfully withdraw his approval.')
else:
doctor.status = 1
messages.success(request, 'Selected doctor are successfully approved.')
doctor.save()
return redirect('view_doctor')

@login_required(login_url="login")
def User_Home(request):
return render(request,'patient_home.html')

@login_required(login_url="login")
def Doctor_Home(request):
return render(request,'doctor_home.html')

def About(request):
return render(request,'about.html')

def Contact(request):
return render(request,'contact.html')

def Gallery(request):
return render(request,'gallery.html')

def Login_User(request):
error = ""
if request.method == "POST":
u = request.POST['uname']
p = request.POST['pwd']
user = authenticate(username=u, password=p)
sign = ""
if user:
try:
sign = Patient.objects.get(user=user)
except:
pass
if sign:
login(request, user)
error = "pat1"
else:
pure=False
try:
pure = Doctor.objects.get(status=1,user=user)
except:
pass
if pure:
122
login(request, user)
error = "pat2"
else:
login(request, user)
error="notmember"
else:
error="not"
d = {'error': error}
return render(request, 'login.html', d)

def Login_admin(request):
error = ""
if request.method == "POST":
u = request.POST['uname']
p = request.POST['pwd']
user = authenticate(username=u, password=p)
if user.is_staff:
login(request, user)
error="pat"
else:
error="not"
d = {'error': error}
return render(request, 'admin_login.html', d)

def Signup_User(request):
error = ""
if request.method == 'POST':
f = request.POST['fname']
l = request.POST['lname']
u = request.POST['uname']
e = request.POST['email']
p = request.POST['pwd']
d = request.POST['dob']
con = request.POST['contact']
add = request.POST['add']
type = request.POST['type']
im = request.FILES['image']
dat = datetime.date.today()
user = User.objects.create_user(email=e, username=u, password=p, first_name=f,last_name=l)
if type == "Patient":
Patient.objects.create(user=user,contact=con,address=add,image=im,dob=d)
else:
Doctor.objects.create(dob=d,image=im,user=user,contact=con,address=add,status=2)
error = "create"
d = {'error':error}
return render(request,'register.html',d)

def Logout(request):
logout(request)
return redirect('home')

123
@login_required(login_url="login")
def Change_Password(request):
sign = 0
user = User.objects.get(username=request.user.username)
error = ""
if not request.user.is_staff:
try:
sign = Patient.objects.get(user=user)
if sign:
error = "pat"
except:
sign = Doctor.objects.get(user=user)
terror = ""
if request.method=="POST":
n = request.POST['pwd1']
c = request.POST['pwd2']
o = request.POST['pwd3']
if c == n:
u = User.objects.get(username__exact=request.user.username)
u.set_password(n)
u.save()
terror = "yes"
else:
terror = "not"
d = {'error':error,'terror':terror,'data':sign}
return render(request,'change_password.html',d)

def preprocess_inputs(df, scaler):


df = df.copy()
# Split df into X and y
y = df['target'].copy()
X = df.drop('target', axis=1).copy()
X = pd.DataFrame(scaler.fit_transform(X), columns=X.columns)
return X, y

def prdict_heart_disease(list_data):
csv_file = Admin_Helath_CSV.objects.get(id=1)
df = pd.read_csv(csv_file.csv_file)

X = df[['age','sex','cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thalach', 'exang', 'oldpeak', 'slope', 'ca',
'thal']]
y = df['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8, random_state=0)
nn_model = GradientBoostingClassifier(n_estimators=100,learning_rate=1.0,max_depth=1,
random_state=0)
nn_model.fit(X_train, y_train)
pred = nn_model.predict([list_data])
print("Neural Network Accuracy: {:.2f}%".format(nn_model.score(X_test, y_test) * 100))
print("Prdicted Value is : ", format(pred))
124
dataframe = str(df.head())
return (nn_model.score(X_test, y_test) * 100),(pred)

@login_required(login_url="login")
def add_doctor(request,pid=None):
doctor = None
if pid:
doctor = Doctor.objects.get(id=pid)
if request.method == "POST":
form = DoctorForm(request.POST, request.FILES, instance = doctor)
if form.is_valid():
new_doc = form.save()
new_doc.status = 1
if not pid:
user = User.objects.create_user(password=request.POST['password'],
username=request.POST['username'], first_name=request.POST['first_name'],
last_name=request.POST['last_name'])
new_doc.user = user
new_doc.save()
return redirect('view_doctor')
d = {"doctor": doctor}
return render(request, 'add_doctor.html', d)

@login_required(login_url="login")
def add_heartdetail(request):
if request.method == "POST":
# list_data = [57, 0, 1, 130, 236, 0, 0, 174, 0, 0.0, 1, 1, 2]
list_data = []
value_dict = eval(str(request.POST)[12:-1])
count = 0
for key,value in value_dict.items():
if count == 0:
count =1
continue
if key == "sex" and value[0] == "Male" or value[0] == 'male' or value[0]=='m' or value[0] == 'M':
list_data.append(0)
continue
elif key == "sex":
list_data.append(1)
continue
list_data.append(value[0])

# list_data = [57, 0, 1, 130, 236, 0, 0, 174, 0, 0.0, 1, 1, 2]


accuracy,pred = prdict_heart_disease(list_data)
patient = Patient.objects.get(user=request.user)
Search_Data.objects.create(patient=patient, prediction_accuracy=round(accuracy,2),
result=pred[0], values_list=list_data,predict_for="Heart Prediction")
rem = int(pred[0])
print("Result = ",rem)
if pred[0] == 0:
pred = "<span style='color:green'>You are healthy</span>"
125
else:
pred = "<span style='color:red'>You are Unhealthy, Need to Checkup.</span>"
return redirect('predict_desease', str(rem), str(round(accuracy,2)))
return render(request, 'add_heartdetail.html')

@login_required(login_url="login")
def predict_desease(request, pred, accuracy):
doctor = Doctor.objects.filter(address__icontains=Patient.objects.get(user=request.user).address)
d = {'pred': pred, 'accuracy':accuracy, 'doctor':doctor}
return render(request, 'predict_disease.html', d)

@login_required(login_url="login")
def view_search_pat(request):
doc = None
try:
doc = Doctor.objects.get(user=request.user)
data = Search_Data.objects.filter(patient__address__icontains=doc.address).order_by('-id')
except:
try:
doc = Patient.objects.get(user=request.user)
data = Search_Data.objects.filter(patient=doc).order_by('-id')
except:
data = Search_Data.objects.all().order_by('-id')
return render(request,'view_search_pat.html',{'data':data})

@login_required(login_url="login")
def delete_doctor(request,pid):
doc = Doctor.objects.get(id=pid)
doc.delete()
return redirect('view_doctor')

@login_required(login_url="login")
def delete_feedback(request,pid):
doc = Feedback.objects.get(id=pid)
doc.delete()
return redirect('view_feedback')

@login_required(login_url="login")
def delete_patient(request,pid):
doc = Patient.objects.get(id=pid)
doc.delete()
return redirect('view_patient')

@login_required(login_url="login")
def delete_searched(request,pid):
doc = Search_Data.objects.get(id=pid)
doc.delete()
return redirect('view_search_pat')

@login_required(login_url="login")
def View_Doctor(request):
126
doc = Doctor.objects.all()
d = {'doc':doc}
return render(request,'view_doctor.html',d)

@login_required(login_url="login")
def View_Patient(request):
patient = Patient.objects.all()
d = {'patient':patient}
return render(request,'view_patient.html',d)

@login_required(login_url="login")
def View_Feedback(request):
dis = Feedback.objects.all()
d = {'dis':dis}
return render(request,'view_feedback.html',d)

@login_required(login_url="login")
def View_My_Detail(request):
terror = ""
user = User.objects.get(id=request.user.id)
error = ""
try:
sign = Patient.objects.get(user=user)
error = "pat"
except:
sign = Doctor.objects.get(user=user)
d = {'error': error,'pro':sign}
return render(request,'profile_doctor.html',d)

@login_required(login_url="login")
def Edit_Doctor(request,pid):
doc = Doctor.objects.get(id=pid)
error = ""
# type = Type.objects.all()
if request.method == 'POST':
f = request.POST['fname']
l = request.POST['lname']
e = request.POST['email']
con = request.POST['contact']
add = request.POST['add']
cat = request.POST['type']
try:
im = request.FILES['image']
doc.image=im
doc.save()
except:
pass
dat = datetime.date.today()
doc.user.first_name = f
doc.user.last_name = l
doc.user.email = e
127
doc.contact = con
doc.category = cat
doc.address = add
doc.user.save()
doc.save()
error = "create"
d = {'error':error,'doc':doc,'type':type}
return render(request,'edit_doctor.html',d)

@login_required(login_url="login")
def Edit_My_deatail(request):
terror = ""
print("Hii welvome")
user = User.objects.get(id=request.user.id)
error = ""
# type = Type.objects.all()
try:
sign = Patient.objects.get(user=user)
error = "pat"
except:
sign = Doctor.objects.get(user=user)
if request.method == 'POST':
f = request.POST['fname']
l = request.POST['lname']
e = request.POST['email']
con = request.POST['contact']
add = request.POST['add']
try:
im = request.FILES['image']
sign.image = im
sign.save()
except:
pass
to1 = datetime.date.today()
sign.user.first_name = f
sign.user.last_name = l
sign.user.email = e
sign.contact = con
if error != "pat":
cat = request.POST['type']
sign.category = cat
sign.save()
sign.address = add
sign.user.save()
sign.save()
terror = "create"
d = {'error':error,'terror':terror,'doc':sign}
return render(request,'edit_profile.html',d)

@login_required(login_url='login')
def sent_feedback(request):
128
terror = None
if request.method == "POST":
username = request.POST['uname']
message = request.POST['msg']
username = User.objects.get(username=username)
Feedback.objects.create(user=username, messages=message)
terror = "create"
return render(request, 'sent_feedback.html',{'terror':terror})

def add_genralhealth(request):
predictiondata = None
deseaseli = []
if request.method=="POST":
for i,j in request.POST.items():
if "csrfmiddlewaretoken" != i:
deseaseli.append(i)
# training.csv
DATA_PATH = Admin_Helath_CSV.objects.get(id=2)
#df = pd.read_csv(csv_file.csv_file)
#DATA_PATH = "c:/Users/bhuwa/OneDrive/Desktop/dataset/Training.csv"
data = pd.read_csv(DATA_PATH.csv_file).dropna(axis = 1)

# Checking whether the dataset is balanced or not


disease_counts = data["prognosis"].value_counts()
temp_df = pd.DataFrame({
"Disease": disease_counts.index,
"Counts": disease_counts.values
})

plt.figure(figsize = (18,8))
sns.barplot(x = "Disease", y = "Counts", data = temp_df)
plt.xticks(rotation=90)
# plt.show()

# Encoding the target value into numerical


# value using LabelEncoder
encoder = LabelEncoder()
data["prognosis"] = encoder.fit_transform(data["prognosis"])

X = data.iloc[:,:-1]
y = data.iloc[:, -1]
X_train, X_test, y_train, y_test =train_test_split(
X, y, test_size = 0.2, random_state = 24)

symptoms = X.columns.values
symptom_index = {}
for index, value in enumerate(symptoms):
129
symptom = " ".join([i.capitalize() for i in value.split("_")])
symptom_index[symptom] = index

data_dict = {
"symptom_index":symptom_index,
"predictions_classes":encoder.classes_
}

final_svm_model = SVC()
final_nb_model = GaussianNB()
final_rf_model = RandomForestClassifier(random_state=18)
final_svm_model.fit(X, y)
final_nb_model.fit(X, y)
final_rf_model.fit(X, y)

#Testing.csv
DATA_PATH2 = Admin_Helath_CSV.objects.get(id=3)
test_data = pd.read_csv(DATA_PATH2.csv_file).dropna(axis=1)

test_X = test_data.iloc[:, :-1]


test_Y = encoder.transform(test_data.iloc[:, -1])

svm_preds = final_svm_model.predict(test_X)
nb_preds = final_nb_model.predict(test_X)
rf_preds = final_rf_model.predict(test_X)

final_preds = [mode([i,j,k])[0][0] for i,j,


k in zip(svm_preds, nb_preds, rf_preds)]

print(f"Accuracy on Test dataset by the combined model\


: {accuracy_score(test_Y, final_preds)*100}")

cf_matrix = confusion_matrix(test_Y, final_preds)


plt.figure(figsize=(12,8))

sns.heatmap(cf_matrix, annot = True)


# plt.title("Confusion Matrix for Combined Model on Test Dataset")
# # plt.show()

def predictDisease(symptoms):
# print("All Symptoms = ", symptoms)
# symptoms = symptoms.split(",")

# # creating input data for the models


input_data = [0] * len(data_dict["symptom_index"])
for symptom in symptoms:
index = data_dict["symptom_index"][symptom]
input_data[index] = 1

# reshaping the input data and converting it


# into suitable format for model predictions
130
input_data = np.array(input_data).reshape(1,-1)

# generating individual outputs


rf_prediction = data_dict["predictions_classes"][final_rf_model.predict(input_data)[0]]
nb_prediction = data_dict["predictions_classes"][final_nb_model.predict(input_data)[0]]
svm_prediction = data_dict["predictions_classes"][final_svm_model.predict(input_data)[0]]

# making final prediction by taking mode of all predictions


final_prediction = mode([rf_prediction, nb_prediction, svm_prediction])[0][0]
predictions = {
"RandomForestClassifier Prediction": rf_prediction,
"GaussianNB Prediction": nb_prediction,
"SVC Prediction": svm_prediction,
"Final Prediction":final_prediction
}
return predictions

# Testing the function


predictiondata = predictDisease(deseaseli)
patient = Patient.objects.get(user=request.user)
Search_Data.objects.create(patient=patient, prediction_accuracy=round(accuracy_score(test_Y,
final_preds)*100,2), result=predictiondata["Final Prediction"], values_list=deseaseli,
predict_for="General Health Prediction")

# print(deseaseli)
alldisease = ['Itching','Skin Rash','Nodal Skin Eruptions','Continuous
Sneezing','Shivering','Chills','Joint Pain', 'Stomach Pain','Acidity','Ulcers On Tongue','Muscle
Wasting','Vomiting','Burning Micturition','Spotting Urination','Fatigue','Weight Gain','Anxiety','Cold
Hands And Feets','Mood Swings','Weight Loss','Restlessness','Lethargy','Patches In Throat','Irregular
Sugar Level','Cough','High Fever','Sunken Eyes','Breathlessness','Sweating','Dehydration',
'Indigestion','Headache','Yellowish Skin','Dark Urine','Nausea','Loss Of Appetite','Pain Behind
The Eyes','Back Pain','Constipation','Abdominal Pain','Diarrhoea','Mild Fever','Yellow
Urine','Yellowing Of Eyes','Acute Liver Failure','Fluid Overload','Swelling Of Stomach','Swelled
Lymph Nodes','Malaise','Blurred And Distorted Vision','Phlegm','Throat Irritation','Redness Of
Eyes','Sinus Pressure','Runny Nose','Congestion','Chest Pain','Weakness In Limbs','Fast Heart Rate',
'Pain During Bowel Movements','Pain In Anal Region','Bloody Stool','Irritation In Anus','Neck
Pain','Dizziness','Cramps','Bruising','Obesity','Swollen Legs','Swollen Blood Vessels','Puffy Face And
Eyes','Enlarged Thyroid','Brittle Nails','Swollen Extremeties','Excessive Hunger','Extra Marital
Contacts','Drying And Tingling Lips','Slurred Speech','Knee Pain','Hip Joint Pain','Muscle
Weakness','Stiff Neck','Swelling Joints','Movement Stiffness','Spinning Movements','Loss Of
Balance','Unsteadiness','Weakness Of One Body Side','Loss Of Smell','Bladder Discomfort','Continuous
Feel Of Urine','Passage Of Gases','Internal Itching','Toxic Look (Typhos)',
'Depression','Irritability','Muscle Pain','Altered Sensorium','Red Spots Over Body','Belly
Pain','Abnormal Menstruation','Dischromic Patches','Watering From Eyes','Increased
Appetite','Polyuria','Family History','Mucoid Sputum','Rusty Sputum','Lack Of Concentration',
'Visual Disturbances','Receiving Blood Transfusion','Receiving Unsterile
Injections','Coma','Stomach Bleeding', 'Distention Of Abdomen','History Of Alcohol
Consumption','Fluid Overload','Blood In Sputum','Prominent Veins On Calf','Palpitations','Painful
Walking','Pus Filled Pimples', 'Blackheads','Scurring','Skin Peeling','Silver Like Dusting','Small Dents
In Nails','Inflammatory Nails','Blister','Red Sore Around Nose','Yellow Crust Ooze','Prognosis']
return render(request,'add_genralhealth.html', {'alldisease':alldisease,
131
'predictiondata':predictiondata})

def search_blood(request):
data = Blood_Donation.objects.filter(status="Approved")
if request.method == "POST":
bg = request.POST['bg']
place = request.POST['place']
user = Patient.objects.get(user=request.user)
Blood_Donation.objects.create(blood_group=bg, user=user, purpose="Request for Blood",
status="Pending", place=place)
messages.success(request, "Request Generated.")
return redirect('search_blood')
return render(request, 'search_blood.html', {'data':data})

def donate_blood(request):
if request.method == "POST":
bg = request.POST['bg']
place = request.POST['place']
user = Patient.objects.get(user=request.user)
data = Blood_Donation.objects.create(blood_group=bg, user=user, purpose="Blood Donor",
status="Pending", place=place)
messages.success(request, "Added Your Detail.")
return redirect('donate_blood')
return render(request, 'donate_blood.html')

def request_blood(request):
mydata = request.GET.get('action',0)
data = Blood_Donation.objects.filter(purpose="Request for Blood")
if mydata:
data = data.filter(status=mydata)
return render(request, 'request_blood.html', {'data':data})

def donator_blood(request):
mydata = request.GET.get('action',0)
data = Blood_Donation.objects.filter(purpose="Blood Donor")
if mydata:
data = data.filter(status=mydata)
return render(request, 'donator_blood.html', {'data':data})

def change_status(request,pid):
data = Blood_Donation.objects.get(id=pid)
url = request.GET.get('data')
if data.status == "Approved":
data.status = "Pending"
data.save()
else:
data.status = "Approved"
data.save()
return HttpResponseRedirect(url)
132
Urls.py

"""HealthDesease URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from healthapp.views import *
# from .api import router

urlpatterns = [
# path('api/sensoviz/', include(router.urls)),
path('admin/', admin.site.urls),
path('', Home, name="home"),
path('patient_home', User_Home,name="patient_home"),
path('doctor_home', Doctor_Home,name="doctor_home"),
path('admin_home', Admin_Home,name="admin_home"),
path('about', About,name="about"),
path('contact', Contact,name="contact"),
path('gallery', Gallery,name="gallery"),
path('login', Login_User,name="login"),
path('login_admin', Login_admin,name="login_admin"),
path('signup', Signup_User,name="signup"),
path('logout', Logout,name="logout"),
path('change_password', Change_Password,name="change_password"),
# path('prdict_heart_disease', prdict_heart_disease,name="prdict_heart_disease"),
path('add_heartdetail', add_heartdetail,name="add_heartdetail"),
path('view_search_pat', view_search_pat,name="view_search_pat"),

path('view_doctor', View_Doctor,name="view_doctor"),
path('add_doctor', add_doctor,name="add_doctor"),
path('change_doctor/<int:pid>/', add_doctor,name="change_doctor"),
path('view_patient', View_Patient,name="view_patient"),
path('view_feedback', View_Feedback,name="view_feedback"),
path('edit_profile', Edit_My_deatail,name="edit_profile"),
133
path('profile_doctor', View_My_Detail,name="profile_doctor"),
path('sent_feedback', sent_feedback,name="sent_feedback"),

path('delete_searched/<int:pid>', delete_searched, name="delete_searched"),


path('delete_doctor<int:pid>', delete_doctor, name="delete_doctor"),
path('assign_status<int:pid>', assign_status, name="assign_status"),
path('delete_patient<int:pid>', delete_patient, name="delete_patient"),
path('delete_feedback<int:pid>', delete_feedback, name="delete_feedback"),
path('predict_desease/<str:pred>/<str:accuracy>/', predict_desease, name="predict_desease"),

path('add_genralhealth', add_genralhealth, name="add_genralhealth"),

path('search_blood', search_blood, name="search_blood"),


path('donate_blood', donate_blood, name="donate_blood"),

path('request_blood', request_blood, name="request_blood"),


path('donator_blood', donator_blood, name="donator_blood"),

path('change_status/<int:pid>/', change_status, name="change_status")

]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

134
SCREENSHOTS

135
136
137
138
139
140
141
142
143

You might also like