Artificial Intelligence Project

PetPulse
AI

An intelligent veterinary diagnostic system that detects diseases in Dogs, Cats, and Cattle — and plans the optimal treatment path — using hybrid AI reasoning.

Decision Tree Naive Bayes A* Search Flask REST API
PATIENT ASSESSMENT · LIVE
Bruno · Golden Retriever · 3 yrs
BODY TEMP
40.2°C
HEART RATE
118 bpm
PRIMARY SYM.
Vomiting
SECONDARY
Diarrhea
AI DIAGNOSIS
Canine Parvovirus
Confidence: 87.3%
⚠ EMERGENCY Engine: Decision Tree
01 / 10
The Challenge

Veterinary diagnosis is slow,
expensive, and error-prone.

Delayed Diagnosis
Critical diseases like Canine Parvovirus and Bovine Respiratory Disease worsen rapidly. Every hour without a correct diagnosis increases mortality risk significantly.
6–24h
Average wait for specialist consultation
🧩
Overlapping Symptoms
Fever + Lethargy + Appetite Loss appears across 12+ different diseases. Distinguishing them requires systematic probabilistic reasoning — not guesswork.
68
Distinct disease classes in our dataset
📋
No Treatment Roadmap
Even after a correct diagnosis, finding the optimal step-by-step treatment sequence — especially with cost and urgency constraints — is non-trivial.
A*
Search finds the lowest-cost path every time
📊
Incomplete Field Data
Rural vets and field workers often have only partial information. The system must make intelligent decisions with missing values — gracefully.
2 Engines
Decision Tree for full data · Bayes for partial
02 / 10
Architecture

How PetPulse AI works

DIAGNOSIS PIPELINE
1
Symptom Input
Vet or owner enters up to 4 symptoms, binary flags (vomiting, diarrhea, etc.), and vitals via the HTML frontend or REST API.
2
Preprocessing
Label encoding, binary flag mapping, StandardScaler normalization. Automatic handling of missing or partial values.
3
Engine Routing
Complete input → Decision Tree (Gini, max_depth=5). Partial input → Naive Bayes with Laplace smoothing. Both return ranked probabilities.
4
A* Treatment Path
f(n) = g(n) + h(n) heuristic search finds the minimum-cost step sequence from triage to recovery discharge.
5
JSON Response
Top-5 ranked diseases with probabilities, optimal treatment path, clinical protocols, and urgency level returned via /api/diagnose.
TECHNOLOGY STACK
🐍
Python 3.11 + Flask
REST backend, CORS-enabled, auto-trains on startup
Backend
🌲
scikit-learn Decision Tree
Gini criterion · max_depth=5 · 75/25 split
ML
🎲
Naive Bayes (custom)
Log-space arithmetic + Laplace smoothing
ML
A* Search (custom heapq)
5 disease-specific graphs + generic fallback
AI
🐼
pandas + NumPy
Dataset loading, feature engineering, encoding
Data
🌐
HTML / JS Frontend
Standalone with embedded JS fallback engine
Frontend
03 / 10
Dataset & Preprocessing

Turning raw vet records into ML-ready features

pet_disease_full_merged.csv
215+
Records
16
Features
68
Disease classes
3
Animal types
Animal Type, BreedCategorical
Age, Heart Rate, Body TempNumerical
Symptom 1–4Multi-label
Vomiting, Diarrhea, Coughing…Binary Flag
Disease PredictionTarget
PREPROCESSING PIPELINE
01
Missing Value Imputation
Categorical columns filled with mode. Numerical columns filled with median. Prevents data leakage.
02
Temperature Parsing
Strips "39.2°C"39.2 float. Handles inconsistent formatting across records.
03
Binary Flag Encoding
Yes/No symptoms → 1/0. Vomiting, Diarrhea, Coughing, Lameness, Skin Lesions, and more.
04
Label Encoding
Categorical features (Animal Type, Breed, Symptoms) mapped to integer indices via LabelEncoder with fitted vocabularies.
05
StandardScaler Normalization
Age, Heart Rate, and Body Temperature scaled to zero-mean, unit-variance. Prevents large-range features dominating the tree splits.
04 / 10
Machine Learning · Engine 1

Decision Tree Classifier

When complete patient data is available, the Decision Tree runs — splitting on the most informative feature at each node using the Gini impurity criterion.

SIMPLIFIED TREE STRUCTURE (depth=3)
≤ 0 ≥ 1 No Yes ≤ 38° ≥ 39° Vomiting Gini=0.82 · n=215 Animal Type Gini=0.76 · n=118 Body Temp Gini=0.71 · n=97 Gastroenteritis p=0.72 · n=32 Parvovirus p=0.85 · n=24 URI · FIP p=0.68 · n=41 Bovine BRD p=0.91 · n=20 Decision node Leaf / prediction Orange = disease label Green = Gini / confidence
Test Accuracy (75/25 split)
~92%
Hyperparameters
criterion
gini
max_depth
5
min_samples_leaf
1
random_state
65
When it activates
All 4 symptom slots filled AND at least 4 binary clinical flags provided. Produces a full feature vector for tree traversal from root to leaf.
Output
Top-5 diseases ranked by predict_proba() — the probability mass at the predicted leaf node.
05 / 10
Machine Learning · Engine 2

Naïve Bayes Inference

When input is partial or incomplete, Naive Bayes takes over — computing posterior probabilities over all disease classes using only the features that are available.

// Posterior (log-space for underflow safety)
log P(D | X) = log P(D)
    + Σ log P(xᵢ | D)

// Laplace smoothing — avoids zero prob
P(x|D) = (count(x,D) + 1) / (|D| + |V|)
EXAMPLE OUTPUT · partial input (Fever + Coughing)
Disease Probability Score
Bovine Resp. Disease
78.2%
Kennel Cough
62.1%
Canine Distemper
48.5%
URI (Cat)
31.3%
Bovine TB
18.0%
WHY NAIVE BAYES FOR PARTIAL INPUT
🔢
Log-space arithmetic — multiplying many small probabilities causes floating-point underflow. Log sums keep everything numerically stable.
🛡️
Laplace smoothing — any symptom not seen for a disease gets probability (0+1)/(n+|V|) instead of zero, preventing a single missing feature from killing a valid hypothesis.
🔀
Handles missing features naturally — just skip terms whose feature is absent. No imputation needed; the posterior simply uses fewer terms.
O(k · f) inference — k disease classes × f observed features. Effectively instant even with 68 classes.
📍
Prior probabilities encode base disease rates in the dataset, so rare diseases aren't given equal weight to common ones.
06 / 10
Pathfinding · Treatment Planning

A* Optimal Treatment Routing

After diagnosis, A* search navigates a disease-specific treatment graph — finding the lowest-cost path from initial triage to full recovery discharge.

A* EVALUATION FUNCTION
f(n) = g(n) + h(n)
gActual cost from start node to current node (treatment steps taken so far)
hAdmissible heuristic — remaining steps to recovery (never overestimates → guarantees optimality)
fPriority score used to order the open heap. Always expand lowest-f node next.
GRAPH PROPERTIES
5 disease-specific graphs for Parvovirus, Bovine TB, URI, FIP, and Bovine BRD — each with custom node weights reflecting clinical urgency.
1 generic fallback graph — Emergency Triage → Diagnostic Workup → Stabilisation → Targeted Treatment → Recovery — for any disease without a specific graph.
Min-heap (heapq) ensures O(E log V) complexity. Visited set prevents re-expansion. Guaranteed optimal when h is admissible.
07 / 10
Worked Examples

Three cases. Three animals.
Three different engines.

🐕
Bruno · Golden Retriever
Dog · 3 yrs · Full data → Decision Tree
Symptom 1Vomiting
Symptom 2Diarrhea
Symptom 3Lethargy
Symptom 4Dehydration
Body Temp40.2°C
Heart Rate118 bpm
Vomiting flagYES
Diarrhea flagYES
Canine Parvovirus
Decision Tree · confidence 87.3%
⚠ EMERGENCY
Treatment path: Triage & Isolation → IV Fluids → Antiemetics → Antibiotics → Nutritional Support → Monitoring → Discharge
🐈
Luna · Siamese
Cat · 5 yrs · Partial data → Naive Bayes
Symptom 1Sneezing
Symptom 2Nasal Discharge
Symptom 3— unknown
Symptom 4— unknown
Coughing flagYES
Body Tempnot recorded
EngineNaive Bayes
Upper Respiratory Infection
Naive Bayes · posterior 72.1%
MODERATE
Treatment path: Clinical Assessment → Nasal Swab → Antibiotic Therapy → Nebulization → Nutritional Support → Discharge
🐄
Herd Animal · Holstein
Cow · 4 yrs · Full data → Decision Tree
Symptom 1Coughing
Symptom 2Fever
Symptom 3Nasal Discharge
Symptom 4Labored Breathing
Body Temp40.8°C
Coughing flagYES
Labored BreathingYES
Bovine Respiratory Disease
Decision Tree · confidence 91.0%
⬆ HIGH
Treatment path: Isolation & Rest → Vitals Check → Tulathromycin → NSAID → Bronchodilator → Nutrition → Return to Herd
08 / 10
REST API

Flask backend, ready to integrate

The system exposes a clean REST interface. Any frontend — web, mobile, or embedded — can query it. The model trains automatically on startup from the CSV.

ENDPOINTS · http://localhost:5000
GET
/api/health
Ping — confirms backend is running. Returns record count, disease count, and active model name.
POST
/api/diagnose
Main inference endpoint. Accepts full patient session JSON. Returns ranked diseases, A* treatment path, treatment text, and prevention advice.
GET
/api/symptoms
Returns all unique symptom values in the dataset — useful for frontend autocomplete dropdowns.
GET
/api/diseases
Returns the full sorted list of disease classes the model knows about.
SAMPLE RESPONSE · /api/diagnose
{
  "primary_disease": "Canine Parvovirus",
  "engine_used": "Decision Tree (CO4)",
  "input_complete": true,
  "top_diseases": [
    {
      "disease": "Canine Parvovirus",
      "probability": 0.873
    },
    { "disease": "Gastroenteritis", "probability": 0.082 }
  ],
  "treatment_path": {
    "path": [
      { "step": 1, "action": "Triage & Isolation" },
      { "step": 2, "action": "IV Fluid Therapy" },
      { "step": 6, "action": "Recovery & Discharge", "is_goal": true }
    ],
    "total_cost": 7
  },
  "treatment_text": "IV fluid therapy (LRS)...",
  "prevention_text": "MLV CPV-2 vaccine..."
}
09 / 10
Summary & Future Work

PetPulse AI — what we built

🧠
Hybrid Reasoning Engine
Decision Tree for complete data (92% accuracy), Naive Bayes with Laplace smoothing for partial data. Both return ranked, probabilistic diagnoses.
A* Optimal Treatment Planning
5 disease-specific graphs + 1 generic fallback. Guaranteed minimum-cost path from triage to recovery using an admissible heuristic.
🌐
Full-Stack Deployment
Flask REST API, standalone HTML frontend with embedded JS fallback engine that runs without a server. Works offline for demos.
🐾
3 Animal Types · 68 Diseases
Dogs, Cats, and Cattle. Covers emergency conditions (Parvovirus, Bovine TB, FMD) down to moderate cases (Kennel Cough, Ringworm, Gastroenteritis).
POSSIBLE FUTURE EXTENSIONS
Expand dataset to 1,000+ records with verified veterinary sources
Add Random Forest / XGBoost ensemble for higher accuracy
Image-based symptom detection (skin lesions, eye discharge) via CNN
Mobile app (React Native) for field use by rural vets
Real-time IoT integration — wearable sensors for continuous vitals
Multilingual interface (Bengali, Hindi) for South Asian veterinarians
PostgreSQL persistence layer for patient history tracking
QUICK START
$ pip install -r requirements.txt
$ python app.py
# Open index.html in browser
10 / 10