Upload 13 files
Browse filesFiles changed (13)
- Cattle Breed Classification/.envAdded
- Cattle Breed Classification/.env.exampleAdded+6
- Cattle Breed Classification/.gitattributesAdded+4
- Cattle Breed Classification/.gitignoreAdded+7
- Cattle Breed Classification/DockerfileAdded+19
- Cattle Breed Classification/README.mdAdded+143
- Cattle Breed Classification/app/.gitattributesAdded+1
- Cattle Breed Classification/app/class_names.pyAdded+15
- Cattle Breed Classification/app/main.pyAdded+156
- Cattle Breed Classification/models/Cattle.tfliteAdded+3
- Cattle Breed Classification/project.ipynbAdded
- Cattle Breed Classification/requirements.txtAdded+6
- Cattle Breed Classification/test_client.pyAdded+43
123456# Copy this file to `.env` and fill in a real value.# Generate one with: python -c "import secrets; print(secrets.token_hex(24))"API_KEY=replace_this_with_a_real_generated_key
# Optional: override where the model file is loaded fromMODEL_PATH=models/Cattle.Keras1234*.h5 filter=lfs diff=lfs merge=lfs -text
*.keras filter=lfs diff=lfs merge=lfs -text
*.tflite/ filter=lfs diff=lfs merge=lfs -text
*.tflite filter=lfs diff=lfs merge=lfs -text1234567__pycache__/*.pyc.envvenv/.venv/*.log.DS_Store12345678910111213141516171819FROM python:3.11-slim
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends \
libgl1 \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app/ ./app/
COPY models/ ./models/
WORKDIR /app/app
ENV MODEL_PATH=/app/models/Cattle.tflite
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143# Cattle & Buffalo Breed Classification API
An AI-powered image classification API that identifies the breed of Indian cattle and buffaloes from a photograph, built for **Smart India Hackathon (SIH) 2025**.
## Problem Statement
| | ||---|---|| **PS Number** | SIH25004 || **Title** | Image Based Breed Recognition for Cattle and Buffaloes of India || **Organization** | Ministry of Fisheries, Animal Husbandry & Dairying || **Category** | Software || **Theme** | Agriculture, FoodTech & Rural Development |
Field workers under the **Bharat Pashudhan App (BPA)** manually record the breed of cattle and buffaloes during registration, which frequently leads to **breed misclassification** due to the sheer diversity of indigenous breeds and lack of expert knowledge on the ground. This reduces the accuracy of national livestock data and hampers breeding programs run under the **Rashtriya Gokul Mission (RGM)**.
This project addresses that gap with an AI-driven solution: a worker uploads/captures an image of an animal, and the system automatically suggests the most probable breed with a confidence score — improving data accuracy and reducing dependency on manual expertise, so it can be integrated into BPA as a breed-suggestion assist.
## What This Repo Contains
This repo hosts the **backend inference API only**. It loads a trained Keras model (`Cattle.Keras`) and exposes it over HTTP so a separate frontend/UI (built by a teammate) can consume it.
- Accepts an uploaded animal image- Returns the **predicted breed label** and **probability scores for all 50 supported breeds**- Secured with an API key so only authorized clients can call it
## Supported Breeds (50)
Purnea, motu, Himachali Pahari, kherigarh, ghumsari, gaolao, Dangi, Sahiwal, Kankrej, Hariana, nagori, Pulikulam, Kosali, Kangayam, bhelai, Konkan Kapila, Shweta Kapila, Kenkatha, Nimari, ponwar, Lakhimi, Vechur, Krishna_Valley, Nari, Hallikar, Punganur, Amritmahal, Tharparkar, Khariar, Khillari, Ayrshire, badri, thutho, Red_Sindhi, siri, Deoni, Bargur, Poda Thirupu, bachaur, Ongole, Malnad_gidda, dagri, Ladakhi, Mewati, Gir, Rathi, gangatari, Umblachery, Red kandhari, malvi
(Full list also available programmatically via the `/classes` endpoint.)
## Repo Structure
```your-repo/├── app/│ ├── main.py # FastAPI app — /predict (key-protected), /health, /classes│ └── class_names.py # CLASS_NAMES list (50 breeds)│├── models/│ └── Cattle.Keras # trained model (use Git LFS if large)│├── test_client.py # CLI script to test the API├── requirements.txt # Python dependencies├── Dockerfile # container build├── .env.example # template (safe to commit — no real secrets)├── .env # real API_KEY + MODEL_PATH — NOT committed├── .gitignore└── README.md```
## Tech Stack
- **Model**: TensorFlow / Keras (CNN-based image classifier)- **API**: FastAPI + Uvicorn- **Image processing**: Pillow, NumPy- **Deployment**: Docker
## Setup
### 1. Clone and install dependencies```bashgit clone <your-repo-url>cd your-repopip install -r requirements.txt```
### 2. Add your modelPlace your trained model file at `models/Cattle.Keras`.
### 3. Configure environment```bashcp .env.example .env```Then edit `.env` and set a real `API_KEY`:```bashpython -c "import secrets; print(secrets.token_hex(24))"```
### 4. Run locally```bashcd appuvicorn main:app --reload```API will be available at `http://localhost:8000`.
### 5. Run with Docker (alternative)```bashdocker build -t cattle-api .docker run -e API_KEY=your_key_here -p 8000:8000 cattle-api```
## API Reference
### `GET /health`Basic health check and model info.
### `GET /classes`Returns the list of all supported breed classes.
### `POST /predict`Upload an image and get breed predictions. Requires header `x-api-key`.
**Request**```POST /predictHeader: x-api-key: <your key>Body (form-data): file=<image>```
**Response**```json{ "predicted_label": "Sahiwal", "confidence": 0.87, "probabilities": { "Purnea": 0.001, "Sahiwal": 0.87, "...": "... all 50 classes" }}```
### Testing the API```bashpython test_client.py path/to/image.jpg --url http://localhost:8000```
## Integration Notes for Frontend/UI Developer
- Send the API key as an `x-api-key` header on every request to `/predict`- Image should be sent as `multipart/form-data` under the field name `file`- `probabilities` in the response is a dict of all 50 breeds — sort it client-side to show top-N results- `/health` and `/classes` are open (no key required) for convenience
## Team
_Add your team name and member names here._
## License
_Add license info if applicable._1*.tflite filter=lfs diff=lfs merge=lfs -text123456789101112131415CLASS_NAMES = [ 'Purnea', 'motu', 'Himachali Pahari', 'kherigarh', 'ghumsari', 'gaolao', 'Dangi', 'Sahiwal', 'Kankrej', 'Hariana', 'nagori', 'Pulikulam', 'Kosali', 'Kangayam', 'bhelai', 'Konkan Kapila', 'Shweta Kapila', 'Kenkatha', 'Nimari', 'ponwar', 'Lakhimi', 'Vechur', 'Krishna_Valley', 'Nari', 'Hallikar', 'Punganur', 'Amritmahal', 'Tharparkar', 'Khariar', 'Khillari', 'Ayrshire', 'badri', 'thutho', 'Red_Sindhi', 'siri', 'Deoni', 'Bargur', 'Poda Thirupu', 'bachaur', 'Ongole', 'Malnad_gidda', 'dagri', 'Ladakhi', 'Mewati', 'Gir', 'Rathi', 'gangatari', 'Umblachery', 'Red kandhari', 'malvi']
# Sanity check helper (used at startup)def num_classes(): return len(CLASS_NAMES)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156"""
FastAPI service for the Cattle breed classification model (TFLite).
Endpoints:
GET /health -> basic health check + model info
GET /classes -> list of supported class names
POST /predict -> upload an image, get probabilities for all classes + top prediction
"""
import io
import os
import secrets
import logging
import numpy as np
from fastapi import FastAPI, File, UploadFile, HTTPException, Security, Depends
from fastapi.security import APIKeyHeader
from fastapi.middleware.cors import CORSMiddleware
from PIL import Image
import tflite_runtime.interpreter as tflite
from class_names import CLASS_NAMES, num_classes
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("cattle-api")
MODEL_PATH = os.environ.get("MODEL_PATH", "models/Cattle.tflite")
# Set this in your environment / .env before running (never commit it).
# Your friend's UI must send it as a header: x-api-key: <this value>
API_KEY = os.environ.get("API_KEY")
app = FastAPI(
title="Cattle Breed Classifier API",
description="Upload an image of a cattle breed and get class probabilities.",
version="1.0.0",
)
# Allow calls from your friend's UI, served from a different origin.
# For production, replace ["*"] with his frontend's actual domain.
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
api_key_header = APIKeyHeader(name="x-api-key", auto_error=False)
def verify_api_key(provided_key: str = Security(api_key_header)):
if not API_KEY:
# No key configured on the server -> auth disabled (fine for local dev only)
return
if not provided_key or not secrets.compare_digest(provided_key, API_KEY):
raise HTTPException(status_code=401, detail="Invalid or missing API key.")
interpreter = None
input_details = None
output_details = None
input_size = (224, 224) # fallback default; overwritten from interpreter's input shape
@app.on_event("startup")
def load_model():
global interpreter, input_details, output_details, input_size
if not os.path.exists(MODEL_PATH):
raise RuntimeError(
f"Model file not found at '{MODEL_PATH}'. "
f"Place your trained model at that path or set the MODEL_PATH env var."
)
logger.info(f"Loading TFLite model from {MODEL_PATH} ...")
interpreter = tflite.Interpreter(model_path=MODEL_PATH)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Auto-detect expected input size from the model
shape = input_details[0]['shape'] # e.g. [1, 224, 224, 3]
if len(shape) == 4 and shape[1] and shape[2]:
input_size = (int(shape[1]), int(shape[2]))
out_units = output_details[0]['shape'][-1]
if out_units != num_classes():
logger.warning(
f"Model output units ({out_units}) does not match number of "
f"CLASS_NAMES ({num_classes()}). Predictions may be mislabeled."
)
logger.info(f"Model loaded. Input size: {input_size}, output classes: {out_units}")
def preprocess_image(file_bytes: bytes) -> np.ndarray:
try:
img = Image.open(io.BytesIO(file_bytes)).convert("RGB")
except Exception:
raise HTTPException(status_code=400, detail="Uploaded file is not a valid image.")
img = img.resize(input_size)
arr = np.array(img, dtype=np.float32) / 255.0
arr = np.expand_dims(arr, axis=0) # add batch dimension
return arr
@app.get("/health")
def health():
return {
"status": "ok",
"model_loaded": interpreter is not None,
"input_size": input_size,
"num_classes": num_classes(),
}
@app.get("/classes")
def classes():
return {"num_classes": num_classes(), "classes": CLASS_NAMES}
@app.post("/predict")
async def predict(file: UploadFile = File(...), _auth: None = Depends(verify_api_key)):
if interpreter is None:
raise HTTPException(status_code=503, detail="Model is not loaded yet.")
if not file.content_type or not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="Please upload an image file.")
file_bytes = await file.read()
input_tensor = preprocess_image(file_bytes)
interpreter.set_tensor(input_details[0]['index'], input_tensor)
interpreter.invoke()
preds = interpreter.get_tensor(output_details[0]['index'])[0] # shape: (num_classes,)
# If model doesn't already output softmax probabilities, normalize defensively.
if not np.isclose(preds.sum(), 1.0, atol=1e-2):
exp = np.exp(preds - np.max(preds))
preds = exp / exp.sum()
probabilities = {
CLASS_NAMES[i]: float(preds[i]) for i in range(min(len(CLASS_NAMES), len(preds)))
}
top_idx = int(np.argmax(preds))
predicted_label = CLASS_NAMES[top_idx] if top_idx < len(CLASS_NAMES) else str(top_idx)
confidence = float(preds[top_idx])
return {
"predicted_label": predicted_label,
"confidence": confidence,
"probabilities": probabilities,
}123version https://git-lfs.github.com/spec/v1oid sha256:30dbb1d1a789ad4a4a7a34879c4d8d513795c09ad9765299169f1744bfc4323dsize 211367716123456fastapi
uvicorn[standard]
pillow
numpy
python-multipart
tflite-runtime12345678910111213141516171819202122232425262728293031323334353637383940414243"""Simple test client for the Cattle Breed Classifier API.
Usage: python test_client.py path/to/image.jpg python test_client.py path/to/image.jpg --url http://localhost:8000"""
import sysimport argparseimport requests
def main(): parser = argparse.ArgumentParser(description="Test the Cattle Breed Classifier API") parser.add_argument("image_path", help="Path to an image file") parser.add_argument("--url", default="http://localhost:8000", help="Base URL of the API") args = parser.parse_args()
# Health check first health_resp = requests.get(f"{args.url}/health") print("Health:", health_resp.json())
with open(args.image_path, "rb") as f: files = {"file": (args.image_path, f, "image/jpeg")} resp = requests.post(f"{args.url}/predict", files=files)
if resp.status_code != 200: print(f"Error {resp.status_code}: {resp.text}") sys.exit(1)
result = resp.json() print(f"\nPredicted label: {result['predicted_label']}") print(f"Confidence: {result['confidence']:.4f}\n")
print("Top 5 probabilities:") sorted_probs = sorted(result["probabilities"].items(), key=lambda x: x[1], reverse=True) for label, prob in sorted_probs[:5]: print(f" {label:25s} {prob:.4f}")
if __name__ == "__main__": main()Cattle Breed Classification/.envAdded
Cattle Breed Classification/.env.exampleAdded+6
Cattle Breed Classification/.gitattributesAdded+4
Cattle Breed Classification/.gitignoreAdded+7
Cattle Breed Classification/DockerfileAdded+19
Cattle Breed Classification/README.mdAdded+143
Cattle Breed Classification/app/.gitattributesAdded+1
Cattle Breed Classification/app/class_names.pyAdded+15
Cattle Breed Classification/app/main.pyAdded+156
Cattle Breed Classification/models/Cattle.tfliteAdded+3
Cattle Breed Classification/project.ipynbAdded
Cattle Breed Classification/requirements.txtAdded+6
Cattle Breed Classification/test_client.pyAdded+43