MLCoder90 commited on
Commit
a4d3de8
·
verified ·
1 Parent(s): b571eef

Upload 13 files

Browse files
Cattle Breed Classification/.env ADDED
File without changes
Cattle Breed Classification/.env.example ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Copy this file to `.env` and fill in a real value.
2
+ # Generate one with: python -c "import secrets; print(secrets.token_hex(24))"
3
+ API_KEY=replace_this_with_a_real_generated_key
4
+
5
+ # Optional: override where the model file is loaded from
6
+ MODEL_PATH=models/Cattle.Keras
Cattle Breed Classification/.gitattributes ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ *.h5 filter=lfs diff=lfs merge=lfs -text
2
+ *.keras filter=lfs diff=lfs merge=lfs -text
3
+ *.tflite/ filter=lfs diff=lfs merge=lfs -text
4
+ *.tflite filter=lfs diff=lfs merge=lfs -text
Cattle Breed Classification/.gitignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ .env
4
+ venv/
5
+ .venv/
6
+ *.log
7
+ .DS_Store
Cattle Breed Classification/Dockerfile ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+ WORKDIR /app
3
+
4
+ RUN apt-get update && apt-get install -y --no-install-recommends \
5
+ libgl1 \
6
+ && rm -rf /var/lib/apt/lists/*
7
+
8
+ COPY requirements.txt .
9
+ RUN pip install --no-cache-dir -r requirements.txt
10
+
11
+ COPY app/ ./app/
12
+ COPY models/ ./models/
13
+
14
+ WORKDIR /app/app
15
+
16
+ ENV MODEL_PATH=/app/models/Cattle.tflite
17
+
18
+ EXPOSE 8000
19
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Cattle Breed Classification/README.md ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Cattle & Buffalo Breed Classification API
2
+
3
+ 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**.
4
+
5
+ ## Problem Statement
6
+
7
+ | | |
8
+ |---|---|
9
+ | **PS Number** | SIH25004 |
10
+ | **Title** | Image Based Breed Recognition for Cattle and Buffaloes of India |
11
+ | **Organization** | Ministry of Fisheries, Animal Husbandry & Dairying |
12
+ | **Category** | Software |
13
+ | **Theme** | Agriculture, FoodTech & Rural Development |
14
+
15
+ 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)**.
16
+
17
+ 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.
18
+
19
+ ## What This Repo Contains
20
+
21
+ 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.
22
+
23
+ - Accepts an uploaded animal image
24
+ - Returns the **predicted breed label** and **probability scores for all 50 supported breeds**
25
+ - Secured with an API key so only authorized clients can call it
26
+
27
+ ## Supported Breeds (50)
28
+
29
+ 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
30
+
31
+ (Full list also available programmatically via the `/classes` endpoint.)
32
+
33
+ ## Repo Structure
34
+
35
+ ```
36
+ your-repo/
37
+ ├── app/
38
+ │ ├── main.py # FastAPI app — /predict (key-protected), /health, /classes
39
+ │ └── class_names.py # CLASS_NAMES list (50 breeds)
40
+ │
41
+ ├── models/
42
+ │ └── Cattle.Keras # trained model (use Git LFS if large)
43
+ │
44
+ ├── test_client.py # CLI script to test the API
45
+ ├── requirements.txt # Python dependencies
46
+ ├── Dockerfile # container build
47
+ ├── .env.example # template (safe to commit — no real secrets)
48
+ ├── .env # real API_KEY + MODEL_PATH — NOT committed
49
+ ├── .gitignore
50
+ └── README.md
51
+ ```
52
+
53
+ ## Tech Stack
54
+
55
+ - **Model**: TensorFlow / Keras (CNN-based image classifier)
56
+ - **API**: FastAPI + Uvicorn
57
+ - **Image processing**: Pillow, NumPy
58
+ - **Deployment**: Docker
59
+
60
+ ## Setup
61
+
62
+ ### 1. Clone and install dependencies
63
+ ```bash
64
+ git clone <your-repo-url>
65
+ cd your-repo
66
+ pip install -r requirements.txt
67
+ ```
68
+
69
+ ### 2. Add your model
70
+ Place your trained model file at `models/Cattle.Keras`.
71
+
72
+ ### 3. Configure environment
73
+ ```bash
74
+ cp .env.example .env
75
+ ```
76
+ Then edit `.env` and set a real `API_KEY`:
77
+ ```bash
78
+ python -c "import secrets; print(secrets.token_hex(24))"
79
+ ```
80
+
81
+ ### 4. Run locally
82
+ ```bash
83
+ cd app
84
+ uvicorn main:app --reload
85
+ ```
86
+ API will be available at `http://localhost:8000`.
87
+
88
+ ### 5. Run with Docker (alternative)
89
+ ```bash
90
+ docker build -t cattle-api .
91
+ docker run -e API_KEY=your_key_here -p 8000:8000 cattle-api
92
+ ```
93
+
94
+ ## API Reference
95
+
96
+ ### `GET /health`
97
+ Basic health check and model info.
98
+
99
+ ### `GET /classes`
100
+ Returns the list of all supported breed classes.
101
+
102
+ ### `POST /predict`
103
+ Upload an image and get breed predictions. Requires header `x-api-key`.
104
+
105
+ **Request**
106
+ ```
107
+ POST /predict
108
+ Header: x-api-key: <your key>
109
+ Body (form-data): file=<image>
110
+ ```
111
+
112
+ **Response**
113
+ ```json
114
+ {
115
+ "predicted_label": "Sahiwal",
116
+ "confidence": 0.87,
117
+ "probabilities": {
118
+ "Purnea": 0.001,
119
+ "Sahiwal": 0.87,
120
+ "...": "... all 50 classes"
121
+ }
122
+ }
123
+ ```
124
+
125
+ ### Testing the API
126
+ ```bash
127
+ python test_client.py path/to/image.jpg --url http://localhost:8000
128
+ ```
129
+
130
+ ## Integration Notes for Frontend/UI Developer
131
+
132
+ - Send the API key as an `x-api-key` header on every request to `/predict`
133
+ - Image should be sent as `multipart/form-data` under the field name `file`
134
+ - `probabilities` in the response is a dict of all 50 breeds — sort it client-side to show top-N results
135
+ - `/health` and `/classes` are open (no key required) for convenience
136
+
137
+ ## Team
138
+
139
+ _Add your team name and member names here._
140
+
141
+ ## License
142
+
143
+ _Add license info if applicable._
Cattle Breed Classification/app/.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.tflite filter=lfs diff=lfs merge=lfs -text
Cattle Breed Classification/app/class_names.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ CLASS_NAMES = [
2
+ 'Purnea', 'motu', 'Himachali Pahari', 'kherigarh', 'ghumsari', 'gaolao',
3
+ 'Dangi', 'Sahiwal', 'Kankrej', 'Hariana', 'nagori', 'Pulikulam', 'Kosali',
4
+ 'Kangayam', 'bhelai', 'Konkan Kapila', 'Shweta Kapila', 'Kenkatha',
5
+ 'Nimari', 'ponwar', 'Lakhimi', 'Vechur', 'Krishna_Valley', 'Nari',
6
+ 'Hallikar', 'Punganur', 'Amritmahal', 'Tharparkar', 'Khariar', 'Khillari',
7
+ 'Ayrshire', 'badri', 'thutho', 'Red_Sindhi', 'siri', 'Deoni', 'Bargur',
8
+ 'Poda Thirupu', 'bachaur', 'Ongole', 'Malnad_gidda', 'dagri', 'Ladakhi',
9
+ 'Mewati', 'Gir', 'Rathi', 'gangatari', 'Umblachery', 'Red kandhari',
10
+ 'malvi'
11
+ ]
12
+
13
+ # Sanity check helper (used at startup)
14
+ def num_classes():
15
+ return len(CLASS_NAMES)
Cattle Breed Classification/app/main.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FastAPI service for the Cattle breed classification model (TFLite).
3
+
4
+ Endpoints:
5
+ GET /health -> basic health check + model info
6
+ GET /classes -> list of supported class names
7
+ POST /predict -> upload an image, get probabilities for all classes + top prediction
8
+ """
9
+
10
+ import io
11
+ import os
12
+ import secrets
13
+ import logging
14
+
15
+ import numpy as np
16
+ from fastapi import FastAPI, File, UploadFile, HTTPException, Security, Depends
17
+ from fastapi.security import APIKeyHeader
18
+ from fastapi.middleware.cors import CORSMiddleware
19
+ from PIL import Image
20
+ import tflite_runtime.interpreter as tflite
21
+
22
+ from class_names import CLASS_NAMES, num_classes
23
+
24
+ logging.basicConfig(level=logging.INFO)
25
+ logger = logging.getLogger("cattle-api")
26
+
27
+ MODEL_PATH = os.environ.get("MODEL_PATH", "models/Cattle.tflite")
28
+
29
+ # Set this in your environment / .env before running (never commit it).
30
+ # Your friend's UI must send it as a header: x-api-key: <this value>
31
+ API_KEY = os.environ.get("API_KEY")
32
+
33
+ app = FastAPI(
34
+ title="Cattle Breed Classifier API",
35
+ description="Upload an image of a cattle breed and get class probabilities.",
36
+ version="1.0.0",
37
+ )
38
+
39
+ # Allow calls from your friend's UI, served from a different origin.
40
+ # For production, replace ["*"] with his frontend's actual domain.
41
+ app.add_middleware(
42
+ CORSMiddleware,
43
+ allow_origins=["*"],
44
+ allow_methods=["*"],
45
+ allow_headers=["*"],
46
+ )
47
+
48
+ api_key_header = APIKeyHeader(name="x-api-key", auto_error=False)
49
+
50
+
51
+ def verify_api_key(provided_key: str = Security(api_key_header)):
52
+ if not API_KEY:
53
+ # No key configured on the server -> auth disabled (fine for local dev only)
54
+ return
55
+ if not provided_key or not secrets.compare_digest(provided_key, API_KEY):
56
+ raise HTTPException(status_code=401, detail="Invalid or missing API key.")
57
+
58
+
59
+ interpreter = None
60
+ input_details = None
61
+ output_details = None
62
+ input_size = (224, 224) # fallback default; overwritten from interpreter's input shape
63
+
64
+
65
+ @app.on_event("startup")
66
+ def load_model():
67
+ global interpreter, input_details, output_details, input_size
68
+
69
+ if not os.path.exists(MODEL_PATH):
70
+ raise RuntimeError(
71
+ f"Model file not found at '{MODEL_PATH}'. "
72
+ f"Place your trained model at that path or set the MODEL_PATH env var."
73
+ )
74
+
75
+ logger.info(f"Loading TFLite model from {MODEL_PATH} ...")
76
+ interpreter = tflite.Interpreter(model_path=MODEL_PATH)
77
+ interpreter.allocate_tensors()
78
+
79
+ input_details = interpreter.get_input_details()
80
+ output_details = interpreter.get_output_details()
81
+
82
+ # Auto-detect expected input size from the model
83
+ shape = input_details[0]['shape'] # e.g. [1, 224, 224, 3]
84
+ if len(shape) == 4 and shape[1] and shape[2]:
85
+ input_size = (int(shape[1]), int(shape[2]))
86
+
87
+ out_units = output_details[0]['shape'][-1]
88
+ if out_units != num_classes():
89
+ logger.warning(
90
+ f"Model output units ({out_units}) does not match number of "
91
+ f"CLASS_NAMES ({num_classes()}). Predictions may be mislabeled."
92
+ )
93
+
94
+ logger.info(f"Model loaded. Input size: {input_size}, output classes: {out_units}")
95
+
96
+
97
+ def preprocess_image(file_bytes: bytes) -> np.ndarray:
98
+ try:
99
+ img = Image.open(io.BytesIO(file_bytes)).convert("RGB")
100
+ except Exception:
101
+ raise HTTPException(status_code=400, detail="Uploaded file is not a valid image.")
102
+
103
+ img = img.resize(input_size)
104
+ arr = np.array(img, dtype=np.float32) / 255.0
105
+ arr = np.expand_dims(arr, axis=0) # add batch dimension
106
+ return arr
107
+
108
+
109
+ @app.get("/health")
110
+ def health():
111
+ return {
112
+ "status": "ok",
113
+ "model_loaded": interpreter is not None,
114
+ "input_size": input_size,
115
+ "num_classes": num_classes(),
116
+ }
117
+
118
+
119
+ @app.get("/classes")
120
+ def classes():
121
+ return {"num_classes": num_classes(), "classes": CLASS_NAMES}
122
+
123
+
124
+ @app.post("/predict")
125
+ async def predict(file: UploadFile = File(...), _auth: None = Depends(verify_api_key)):
126
+ if interpreter is None:
127
+ raise HTTPException(status_code=503, detail="Model is not loaded yet.")
128
+
129
+ if not file.content_type or not file.content_type.startswith("image/"):
130
+ raise HTTPException(status_code=400, detail="Please upload an image file.")
131
+
132
+ file_bytes = await file.read()
133
+ input_tensor = preprocess_image(file_bytes)
134
+
135
+ interpreter.set_tensor(input_details[0]['index'], input_tensor)
136
+ interpreter.invoke()
137
+ preds = interpreter.get_tensor(output_details[0]['index'])[0] # shape: (num_classes,)
138
+
139
+ # If model doesn't already output softmax probabilities, normalize defensively.
140
+ if not np.isclose(preds.sum(), 1.0, atol=1e-2):
141
+ exp = np.exp(preds - np.max(preds))
142
+ preds = exp / exp.sum()
143
+
144
+ probabilities = {
145
+ CLASS_NAMES[i]: float(preds[i]) for i in range(min(len(CLASS_NAMES), len(preds)))
146
+ }
147
+
148
+ top_idx = int(np.argmax(preds))
149
+ predicted_label = CLASS_NAMES[top_idx] if top_idx < len(CLASS_NAMES) else str(top_idx)
150
+ confidence = float(preds[top_idx])
151
+
152
+ return {
153
+ "predicted_label": predicted_label,
154
+ "confidence": confidence,
155
+ "probabilities": probabilities,
156
+ }
Cattle Breed Classification/models/Cattle.tflite ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:30dbb1d1a789ad4a4a7a34879c4d8d513795c09ad9765299169f1744bfc4323d
3
+ size 211367716
Cattle Breed Classification/project.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
Cattle Breed Classification/requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn[standard]
3
+ pillow
4
+ numpy
5
+ python-multipart
6
+ tflite-runtime
Cattle Breed Classification/test_client.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Simple test client for the Cattle Breed Classifier API.
3
+
4
+ Usage:
5
+ python test_client.py path/to/image.jpg
6
+ python test_client.py path/to/image.jpg --url http://localhost:8000
7
+ """
8
+
9
+ import sys
10
+ import argparse
11
+ import requests
12
+
13
+
14
+ def main():
15
+ parser = argparse.ArgumentParser(description="Test the Cattle Breed Classifier API")
16
+ parser.add_argument("image_path", help="Path to an image file")
17
+ parser.add_argument("--url", default="http://localhost:8000", help="Base URL of the API")
18
+ args = parser.parse_args()
19
+
20
+ # Health check first
21
+ health_resp = requests.get(f"{args.url}/health")
22
+ print("Health:", health_resp.json())
23
+
24
+ with open(args.image_path, "rb") as f:
25
+ files = {"file": (args.image_path, f, "image/jpeg")}
26
+ resp = requests.post(f"{args.url}/predict", files=files)
27
+
28
+ if resp.status_code != 200:
29
+ print(f"Error {resp.status_code}: {resp.text}")
30
+ sys.exit(1)
31
+
32
+ result = resp.json()
33
+ print(f"\nPredicted label: {result['predicted_label']}")
34
+ print(f"Confidence: {result['confidence']:.4f}\n")
35
+
36
+ print("Top 5 probabilities:")
37
+ sorted_probs = sorted(result["probabilities"].items(), key=lambda x: x[1], reverse=True)
38
+ for label, prob in sorted_probs[:5]:
39
+ print(f" {label:25s} {prob:.4f}")
40
+
41
+
42
+ if __name__ == "__main__":
43
+ main()