Skip to main content

EduBotX ML API v2.1.0

REST API for wastewater treatment ML predictions. Optimized for Next.js integration.

  • Base URL: http://localhost:8000
  • Interactive Docs: http://localhost:8000/docs (Swagger UI)
  • Alternative Docs: http://localhost:8000/redoc (ReDoc)
  • Content-Type: application/json
  • CORS: Enabled for all origins

Table of Contents

  1. Response Format
  2. Health & Status
  3. Predictions
  4. Treatment Endpoint (Enhanced)
  5. Reusability V2 (CPCB-aware)
  6. Reference Data
  7. Reports
  8. Batch Processing
  9. Error Handling
  10. Next.js Integration
  11. Legacy Endpoints

Response Format

All endpoints return a standardized response:

{
"status": "success" | "error",
"data": { ... } | null,
"message": "Optional message",
"error": null | "Error description",
"timestamp": "2024-12-02T00:00:00.000Z"
}

1. Health & Status

GET /

Root endpoint - API status check.

Response:

{
"status": "success",
"data": {
"message": "EduBotX ML API is running",
"version": "2.1.0"
},
"message": "API is healthy"
}

GET /health

Detailed health check with model status.

Response:

{
"status": "success",
"data": {
"status": "healthy",
"models": {
"reusability_predictor": true,
"treatment_recommender": true
},
"version": "2.1.0"
}
}

GET /api/models

List available models and their status.

Response:

{
"status": "success",
"data": [
{
"id": "reusability",
"name": "Reusability Predictor",
"version": "1.0",
"loaded": true,
"endpoint": "/api/predict/reusability",
"features": ["flow_rate", "influent_BOD", ...],
"classes": ["irrigation", "industrial_low", ...]
},
{
"id": "reusability_v2",
"name": "Reusability Predictor V2 (with CPCB Compliance)",
"version": "2.0",
"loaded": true,
"endpoint": "/api/predict/reusability/v2"
},
{
"id": "treatment",
"name": "Treatment Recommender",
"version": "1.0",
"loaded": true,
"endpoint": "/api/predict/treatment",
"classes": ["Primary", "Secondary", "Tertiary", "Advanced"]
}
]
}

GET /api/schema/{model_id}

Get input schema for dynamic form generation.

Parameters: model_id = reusability | reusability_v2 | treatment

Response:

{
"status": "success",
"data": {
"model_id": "treatment",
"fields": [
{ "name": "pH", "type": "number", "required": true, "min": 0, "max": 14, "label": "pH Level" },
{ "name": "TSS", "type": "number", "required": true, "min": 0, "label": "TSS (mg/L)" },
{ "name": "Turbidity", "type": "number", "required": true, "min": 0, "label": "Turbidity (NTU)" },
{ "name": "BOD", "type": "number", "required": true, "min": 0, "label": "BOD (mg/L)" },
{ "name": "COD", "type": "number", "required": true, "min": 0, "label": "COD (mg/L)" },
{ "name": "NH4_N", "type": "number", "required": true, "min": 0, "label": "Ammonium Nitrogen (mg/L)" },
{ "name": "Total_Nitrogen", "type": "number", "required": true, "min": 0, "label": "Total Nitrogen (mg/L)" },
{ "name": "Phosphate", "type": "number", "required": true, "min": 0, "label": "Phosphate (mg/L)" },
{ "name": "Fecal_Coliform", "type": "number", "required": true, "min": 0, "label": "Fecal Coliform" },
{ "name": "Oil_Grease", "type": "number", "required": true, "min": 0, "label": "Oil & Grease (mg/L)" },
{ "name": "TDS", "type": "number", "required": true, "min": 0, "label": "TDS (mg/L)" },
{ "name": "Heavy_Metals", "type": "number", "required": true, "min": 0, "label": "Heavy Metals" }
]
}
}

2. Predictions

POST /api/predict/reusability

Predict water reusability class.

Request:

{
"flow_rate": 100,
"influent_BOD": 200,
"influent_COD": 400,
"influent_TSS": 150,
"influent_pH": 7.2,
"influent_TDS": 500,
"aeration_rate": 50,
"chemical_dose": 25,
"sludge_recycle_rate": 30,
"retention_time": 8,
"temperature": 28,
"effluent_BOD_lag1": 20
}

Response:

{
"status": "success",
"data": {
"model": "Reusability Predictor",
"prediction": "irrigation",
"confidence": 0.91,
"probabilities": { "irrigation": 0.91, "industrial_low": 0.07, "not_reusable": 0.02 },
"input_summary": { "flow_rate": 100, "influent_BOD": 200 }
},
"message": "Predicted reusability: irrigation"
}

3. Treatment Endpoint (Enhanced)

POST /api/predict/treatment

Get treatment stage recommendation with comprehensive analysis.

Query Parameters:

ParameterTypeDescription
use_casestring (optional)Target use case: Irrigation, Domestic Use, Industrial Use, Drinking Water, Aquaculture

Request:

{
"pH": 7.5,
"TSS": 120,
"Turbidity": 45,
"BOD": 180,
"COD": 350,
"NH4_N": 25,
"Total_Nitrogen": 40,
"Phosphate": 8,
"Fecal_Coliform": 5000,
"Oil_Grease": 15,
"TDS": 600,
"Heavy_Metals": 0.5
}

Example with use_case:

curl -X POST "http://localhost:8000/api/predict/treatment?use_case=Drinking%20Water" \
-H "Content-Type: application/json" \
-d '{"pH": 7.5, "TSS": 120, ...}'

Response:

{
"status": "success",
"data": {
"model": "Treatment Recommender",
"predicted_stage": "Secondary",
"recommended_stage": "Advanced",
"use_case_applied": "Drinking Water",
"steps": ["Membrane Bioreactor", "Reverse Osmosis", "UV Disinfection", "Ozonation"],
"step_descriptions": {
"Membrane Bioreactor": "Combined biological treatment and membrane filtration",
"Reverse Osmosis": "Remove dissolved salts and contaminants",
"UV Disinfection": "Ultraviolet light pathogen inactivation",
"Ozonation": "Advanced oxidation for micropollutant removal"
},
"cumulative_sequence": [
"Screening", "Grit removal", "Primary sedimentation",
"Aeration / activated sludge", "Secondary clarification",
"Nutrient removal (N&P)", "Filtration", "Disinfection",
"UF/RO", "Activated carbon", "Heavy metal removal", "AOP"
],
"severity_level": "moderate",
"quality_score": 65,
"parameter_status": {
"pH": "Good",
"TSS": "Moderate",
"Turbidity": "Moderate",
"BOD": "Poor",
"COD": "Poor",
"NH4_N": "Poor",
"Total_Nitrogen": "Poor",
"Phosphate": "Poor",
"Fecal_Coliform": "Good",
"Oil_Grease": "Moderate",
"TDS": "Good",
"Heavy_Metals": "Moderate"
},
"chemical_suggestions": {
"chlorine_dose_mg_l": 1.0,
"alum_dose_mg_l": 8,
"recommend_ro": false,
"notes": "These are approximate values. Actual dosing should be determined through jar tests."
},
"risk_assessment": {
"level": "Low",
"reasons": []
},
"input_analysis": { ... }
},
"message": "Recommended treatment: Advanced"
}

Treatment Stages

StageDescriptionUse Cases
PrimaryPhysical treatment (screening, sedimentation)Pre-treatment
SecondaryBiological treatment (activated sludge)Irrigation
TertiaryAdvanced filtration and disinfectionDomestic, Industrial, Aquaculture
AdvancedMembrane processes (RO, UF)Drinking Water

4. Reusability V2 (CPCB-aware)

POST /api/predict/reusability/v2

Enhanced reusability prediction with:

  • ✅ CPCB inland surface water compliance check
  • ✅ Treatment upgrade recommendation
  • ✅ Optional effluent inputs with heuristic estimation
  • ✅ Human-friendly verdict combining model + CPCB status

Request:

{
"flow_rate": 150,
"influent_BOD": 18,
"influent_COD": 36,
"influent_TSS": 22,
"influent_pH": 6.0,
"influent_TDS": 65,
"aeration_rate": 35,
"chemical_dose": 12,
"sludge_recycle_rate": 25,
"retention_time": 6,
"temperature": 25,
"effluent_BOD": 20,
"effluent_COD": 150,
"effluent_TSS": 30,
"effluent_TDS": 800,
"effluent_pH": 7.5
}

Response:

{
"status": "success",
"data": {
"model": "Reusability Predictor V2",
"prediction": "irrigation",
"prediction_display": "Irrigation",
"confidence": 0.674,
"confidence_percent": 67.4,
"probabilities": { "industrial_low": 0.294, "irrigation": 0.674, "not_reusable": 0.032 },
"cpcb_compliance": {
"status": "PASS",
"is_compliant": true,
"reason": "All checked effluent parameters are within limits.",
"records": [
{ "Parameter": "pH", "Limit": "5.5-9.0", "Your Value": 7.5, "Status": "PASS" },
{ "Parameter": "BOD", "Limit": "<= 30 mg/L", "Your Value": 20.0, "Status": "PASS" },
{ "Parameter": "COD", "Limit": "<= 250 mg/L", "Your Value": 150.0, "Status": "PASS" },
{ "Parameter": "TSS", "Limit": "<= 100 mg/L", "Your Value": 30.0, "Status": "PASS" },
{ "Parameter": "TDS", "Limit": "<= 2100 mg/L", "Your Value": 800.0, "Status": "PASS" }
],
"near_miss": []
},
"treatment_upgrade": {
"upgrade_label": "No Upgrade Required",
"upgrade_reason": "Effluent meets CPCB limits. Maintain routine tertiary disinfection and monitoring before using for 'Irrigation' applications."
},
"class_info": {
"purpose": "Agricultural irrigation for crops; monitor salinity.",
"remedies": "Check soil and crop compatibility. Monitor salinity (TDS) and heavy metals."
},
"smart_verdict": {
"status": "safe",
"headline": "Safe for 'Irrigation' reuse and CPCB discharge-compliant.",
"bullets": [
"Model confidence: 67.4%",
"CPCB status: PASS",
"Treatment upgrade: No Upgrade Required"
]
},
"alternatives": [
{ "class": "Industrial Low", "probability": 29.4 }
],
"cpcb_adjusted": false,
"original_prediction": null,
"estimated_values": null,
"input_summary": { ... }
},
"message": "Predicted reusability: Irrigation"
}

Note: If effluent fields are omitted, they are estimated from influent and process parameters and returned under estimated_values.


5. Reference Data

GET /api/class-info

Returns metadata for each reusability class.

Response:

{
"status": "success",
"data": {
"drinking": {
"purpose": "Potable water supply, meeting strict drinking water standards.",
"remedies": "Ensure compliance with WHO/EPA drinking water guidelines."
},
"industrial_high": {
"purpose": "High-quality industrial processes (electronics, pharmaceuticals).",
"remedies": "Monitor for organics and heavy metals; consider polishing steps."
},
"industrial_low": {
"purpose": "General industrial uses like cooling or washing.",
"remedies": "Ensure pH and TDS are within process limits."
},
"irrigation": {
"purpose": "Agricultural irrigation for crops; monitor salinity.",
"remedies": "Check soil and crop compatibility. Monitor TDS and heavy metals."
},
"not_reusable": {
"purpose": "Not suitable for any reuse.",
"remedies": "Requires further treatment before discharge or reuse."
}
}
}

GET /api/cpcb-limits

Returns CPCB inland surface water discharge limits.

Response:

{
"status": "success",
"data": {
"pH_min": 5.5,
"pH_max": 9.0,
"BOD": 30,
"COD": 250,
"TSS": 100,
"TDS": 2100,
"ammonia": 5,
"nitrate": 50,
"phosphate": 5,
"lead": 0.1
}
}

6. Reports

POST /api/report/generate

Generate PDF treatment report.

Request: Same as /api/predict/treatment

Response: PDF file download (application/pdf)

Example:

curl -X POST http://localhost:8000/api/report/generate \
-H "Content-Type: application/json" \
-d '{"pH": 7.5, "TSS": 120, ...}' \
--output report.pdf

7. Batch Processing

POST /api/predict/batch

Process multiple samples in one request.

Request:

{
"model_id": "treatment",
"samples": [
{
"pH": 7.5,
"TSS": 120,
"Turbidity": 45,
"BOD": 180,
"COD": 350,
"NH4_N": 25,
"Total_Nitrogen": 40,
"Phosphate": 8,
"Fecal_Coliform": 5000,
"Oil_Grease": 15,
"TDS": 600,
"Heavy_Metals": 0.5
},
{
"pH": 6.8,
"TSS": 200,
"Turbidity": 80,
"BOD": 250,
"COD": 500,
"NH4_N": 35,
"Total_Nitrogen": 60,
"Phosphate": 12,
"Fecal_Coliform": 15000,
"Oil_Grease": 25,
"TDS": 1200,
"Heavy_Metals": 1.2
}
]
}

Response:

{
"status": "success",
"data": {
"model_id": "treatment",
"total": 2,
"successful": 2,
"results": [
{"index": 0, "success": true, "result": { ... }},
{"index": 1, "success": true, "result": { ... }}
]
}
}

8. Error Handling

StatusDescription
200Success
400Bad request (invalid model_id, etc.)
404Resource not found
422Validation error (with field details)
500Internal server error
503Model not available

Validation Error Response:

{
"status": "error",
"error": "Validation Error",
"message": "pH: Input should be greater than or equal to 0",
"details": [{ "loc": ["body", "pH"], "msg": "...", "type": "..." }],
"timestamp": "2024-12-02T00:00:00.000Z"
}

9. Next.js Integration

TypeScript Client

const ML_API_URL = process.env.NEXT_PUBLIC_ML_API_URL || "http://localhost:8000";

interface APIResponse<T> {
status: "success" | "error";
data: T | null;
message?: string;
error?: string;
timestamp: string;
}

async function predictTreatment(input: TreatmentInput, useCase?: string): Promise<TreatmentResult> {
const url = new URL(`${ML_API_URL}/api/predict/treatment`);
if (useCase) url.searchParams.set("use_case", useCase);

const response = await fetch(url.toString(), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(input),
});

const result: APIResponse<TreatmentResult> = await response.json();
if (result.status === "error") throw new Error(result.error);
return result.data!;
}

React Hook Example

import { useState } from "react";

function useTreatmentPrediction() {
const [data, setData] = useState<TreatmentResult | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);

const predict = async (input: TreatmentInput, useCase?: string) => {
setIsLoading(true);
setError(null);
try {
const result = await predictTreatment(input, useCase);
setData(result);
} catch (e) {
setError(e instanceof Error ? e.message : "Unknown error");
} finally {
setIsLoading(false);
}
};

return { predict, data, isLoading, error };
}

Environment Variables

NEXT_PUBLIC_ML_API_URL=http://localhost:8000

10. Legacy Endpoints

These endpoints are maintained for backward compatibility but are deprecated:

LegacyCurrent
POST /predictPOST /api/predict/reusability
POST /recommend-treatmentPOST /api/predict/treatment

Quick Reference

EndpointMethodDescription
/GETAPI status
/healthGETHealth check
/docsGETSwagger UI
/redocGETReDoc
/api/modelsGETList models
/api/schema/{model_id}GETGet input schema
/api/predict/reusabilityPOSTReusability prediction
/api/predict/reusability/v2POSTReusability + CPCB
/api/predict/treatmentPOSTTreatment recommendation
/api/predict/batchPOSTBatch predictions
/api/class-infoGETClass metadata
/api/cpcb-limitsGETCPCB limits
/api/report/generatePOSTPDF report