Skip to content

rktm0604/crop-recommendation-system

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

8 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🌿 SmartCrop β€” Crop Recommendation System

An intelligent, full-stack crop recommendation platform that analyzes soil nutrients and climate data to deliver data-driven recommendations for optimal crop selection.

Java 17 Spring Boot MySQL Docker MIT License


πŸ“‹ Table of Contents


🌱 Overview

SmartCrop is a production-ready crop recommendation system built with Spring Boot that helps farmers make data-driven decisions. It analyzes soil parameters (Nitrogen, Phosphorus, Potassium, pH) along with real-time weather data to recommend the most suitable crop with a confidence score.

Key Highlights:

  • πŸ§ͺ Rule-based recommendation engine matching soil profiles to ideal crop ranges
  • 🌀️ Real-time weather integration via OpenWeather API
  • πŸ“Š Interactive dashboards with Chart.js visualizations
  • πŸ” JWT-based authentication with role-based access control (Admin, Farmer, Officer)
  • 🐳 Docker-ready for one-command deployment

✨ Features

Feature Description
Soil Analysis Submit NPK, pH, and moisture data for intelligent crop matching
Weather Integration Live weather data from OpenWeather API for climate-aware recommendations
Smart Recommendations Algorithm matches soil + climate to crop ideal ranges with confidence scoring
Role-Based Dashboards Farmer (NPK trends), Admin (crop analytics), Officer (weather trends)
JWT Authentication Secure login with BCrypt passwords and HTTP-only cookie sessions
Modern Landing Page Beautiful hero section with feature cards and gradient design
Responsive UI Mobile-friendly dashboard built with Bootstrap 5 + custom CSS
RESTful API Complete API for programmatic access to all features
Docker Support One-command deployment with MySQL via Docker Compose

πŸ—οΈ Architecture

graph TB
    subgraph Client["πŸ–₯️ Client Layer"]
        LP[Landing Page]
        UI[Dashboard UI<br/>Thymeleaf + Bootstrap 5 + Chart.js]
        API_CLIENT[REST API Clients]
    end

    subgraph Security["πŸ” Security Layer"]
        JWT[JWT Authentication Filter]
        RBAC[Role-Based Access Control]
    end

    subgraph Application["βš™οΈ Application Layer"]
        WC[Web Controller]
        AC[Auth Controller]
        RC[Recommendation Controller]
        SC[Soil Data Controller]
        WEC[Weather Controller]
        DC[Dashboard API Controller]
    end

    subgraph Service["🧠 Service Layer"]
        RS[Recommendation Service<br/>Rule-Based Engine]
        US[User Service]
        SS[Soil Data Service]
        WS[Weather Service]
        DS[Dashboard Service]
    end

    subgraph Data["πŸ’Ύ Data Layer"]
        REPO[JPA Repositories]
        DB[(MySQL / H2)]
        OW[OpenWeather API]
    end

    LP --> WC
    UI --> DC
    API_CLIENT --> AC
    API_CLIENT --> RC
    API_CLIENT --> SC
    Client --> JWT --> RBAC --> Application
    Application --> Service
    RS --> REPO
    SS --> REPO
    DS --> REPO
    WS --> OW
    WS --> REPO
    REPO --> DB
Loading

Data Flow:

  1. User submits soil data (NPK, pH, moisture) + optional location
  2. System fetches real-time weather if location provided
  3. Recommendation engine scores all crops against soil/climate parameters
  4. Best match returned with confidence score and persisted to database
  5. Dashboard visualizations update with new data

πŸ› οΈ Tech Stack

Layer Technology
Backend Spring Boot 3.2, Spring Web, Spring Data JPA, Spring Security
Frontend Thymeleaf, Bootstrap 5, Chart.js, Custom CSS
Database MySQL 8.x (production) Β· H2 (demo mode)
Authentication JWT + BCrypt, HTTP-only cookies
External API OpenWeather API
Build Maven 3.8+, Maven Wrapper
DevOps Docker, Docker Compose
Language Java 17

πŸ“ Project Structure

crop-recommendation-system/
β”œβ”€β”€ πŸ“„ README.md
β”œβ”€β”€ πŸ“„ LICENSE                         # MIT License
β”œβ”€β”€ πŸ“„ CONTRIBUTING.md                 # Contribution guidelines
β”œβ”€β”€ πŸ“„ CHANGELOG.md                    # Version history
β”œβ”€β”€ πŸ“„ .env.example                    # Environment template
β”œβ”€β”€ πŸ“„ .gitignore
β”œβ”€β”€ 🐳 Dockerfile
β”œβ”€β”€ 🐳 docker-compose.yml
β”œβ”€β”€ πŸ“„ pom.xml
β”œβ”€β”€ πŸ“„ run.ps1                         # Quick start script
β”‚
β”œβ”€β”€ src/main/java/com/crop/
β”‚   β”œβ”€β”€ πŸš€ CropRecommendationApplication.java
β”‚   β”‚
β”‚   β”œβ”€β”€ config/                        # Configuration
β”‚   β”‚   β”œβ”€β”€ SecurityConfig.java        #   Spring Security + JWT setup
β”‚   β”‚   β”œβ”€β”€ WebClientConfig.java       #   WebClient for external APIs
β”‚   β”‚   └── DataLoader.java            #   Database seeding
β”‚   β”‚
β”‚   β”œβ”€β”€ controller/                    # Request Handlers
β”‚   β”‚   β”œβ”€β”€ WebController.java         #   Thymeleaf page routes
β”‚   β”‚   β”œβ”€β”€ AuthController.java        #   Login/Register REST API
β”‚   β”‚   β”œβ”€β”€ RecommendationController.java
β”‚   β”‚   β”œβ”€β”€ SoilDataController.java
β”‚   β”‚   β”œβ”€β”€ WeatherController.java
β”‚   β”‚   β”œβ”€β”€ CropController.java
β”‚   β”‚   └── DashboardApiController.java
β”‚   β”‚
β”‚   β”œβ”€β”€ service/                       # Business Logic
β”‚   β”‚   β”œβ”€β”€ RecommendationService.java #   🧠 Core recommendation engine
β”‚   β”‚   β”œβ”€β”€ UserService.java
β”‚   β”‚   β”œβ”€β”€ SoilDataService.java
β”‚   β”‚   β”œβ”€β”€ WeatherService.java
β”‚   β”‚   └── DashboardService.java
β”‚   β”‚
β”‚   β”œβ”€β”€ repository/                    # Data Access
β”‚   β”‚   β”œβ”€β”€ CropRepository.java
β”‚   β”‚   β”œβ”€β”€ RecommendationRepository.java
β”‚   β”‚   β”œβ”€β”€ SoilDataRepository.java
β”‚   β”‚   β”œβ”€β”€ UserRepository.java
β”‚   β”‚   └── WeatherDataRepository.java
β”‚   β”‚
β”‚   β”œβ”€β”€ entity/                        # Database Models
β”‚   β”‚   β”œβ”€β”€ User.java
β”‚   β”‚   β”œβ”€β”€ Crop.java
β”‚   β”‚   β”œβ”€β”€ Recommendation.java
β”‚   β”‚   β”œβ”€β”€ SoilData.java
β”‚   β”‚   β”œβ”€β”€ WeatherData.java
β”‚   β”‚   └── enums/Role.java
β”‚   β”‚
β”‚   β”œβ”€β”€ dto/                           # Data Transfer Objects
β”‚   β”‚   β”œβ”€β”€ LoginRequest.java
β”‚   β”‚   β”œβ”€β”€ LoginResponse.java
β”‚   β”‚   β”œβ”€β”€ RegisterRequest.java
β”‚   β”‚   β”œβ”€β”€ RecommendationRequest.java
β”‚   β”‚   β”œβ”€β”€ RecommendationResponse.java
β”‚   β”‚   β”œβ”€β”€ SoilDataRequest.java
β”‚   β”‚   β”œβ”€β”€ WeatherResponse.java
β”‚   β”‚   └── ApiError.java
β”‚   β”‚
β”‚   β”œβ”€β”€ security/                      # Authentication
β”‚   β”‚   β”œβ”€β”€ JwtAuthenticationFilter.java
β”‚   β”‚   β”œβ”€β”€ JwtUtil.java
β”‚   β”‚   └── CustomUserDetailsService.java
β”‚   β”‚
β”‚   └── exception/                     # Error Handling
β”‚       β”œβ”€β”€ GlobalExceptionHandler.java
β”‚       β”œβ”€β”€ BadRequestException.java
β”‚       └── ResourceNotFoundException.java
β”‚
β”œβ”€β”€ src/main/resources/
β”‚   β”œβ”€β”€ templates/                     # Thymeleaf Views
β”‚   β”‚   β”œβ”€β”€ home.html                  #   Landing page
β”‚   β”‚   β”œβ”€β”€ login.html
β”‚   β”‚   β”œβ”€β”€ register.html
β”‚   β”‚   └── dashboard.html             #   Main dashboard
β”‚   β”œβ”€β”€ static/css/
β”‚   β”‚   └── style.css                  #   Custom styles
β”‚   β”œβ”€β”€ application.properties         #   MySQL config
β”‚   └── application-demo.properties    #   H2 demo config
β”‚
β”œβ”€β”€ database/
β”‚   └── schema.sql                     # DDL + sample data
β”‚
└── docs/
    └── CNDC_Justification.md          # Architecture decisions

πŸš€ Quick Start

Option 1: PowerShell Script (Easiest)

# Production (MySQL required)
.\run.ps1

# Demo mode (no MySQL needed β€” uses H2 in-memory database)
.\run.ps1 -Demo

Option 2: Maven

# With MySQL
mvn spring-boot:run

# With H2 (demo)
mvn spring-boot:run -Dspring-boot.run.profiles=demo

Option 3: Docker (Full Stack)

mvn clean package -DskipTests
docker compose up -d --build

Access: http://localhost:8080

Prerequisites

Requirement For Production For Demo
JDK 17+ βœ… Required βœ… Required
MySQL 8.x βœ… Required ❌ Not needed
Maven βœ… Or use mvnw βœ… Or use mvnw
Docker ❌ Optional ❌ Optional

MySQL Setup

-- Database is auto-created if URL has createDatabaseIfNotExist=true
-- Or create manually:
CREATE DATABASE IF NOT EXISTS crop_recommendation_db;

Update src/main/resources/application.properties with your MySQL password:

spring.datasource.username=root
spring.datasource.password=YOUR_PASSWORD

πŸ“‘ API Reference

All API endpoints require JWT authentication (except auth endpoints).

Authentication

Method Endpoint Description
POST /api/auth/login Login, returns JWT
POST /api/auth/register Register new user

Core APIs

Method Endpoint Role Description
POST /api/recommendation FARMER+ Get crop recommendation
POST /api/soil FARMER+ Submit soil data
GET /api/soil FARMER+ List user's soil data
GET /api/weather/current?location=X ALL Fetch & store weather

Dashboard APIs

Method Endpoint Role Description
GET /api/dashboard/farmer FARMER NPK trends + recommendations
GET /api/dashboard/admin ADMIN Most recommended crops
GET /api/dashboard/officer?location=X OFFICER Weather trends

Example: Get Recommendation

# 1. Login
TOKEN=$(curl -s -X POST http://localhost:8080/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"farmer@crop.com","password":"password123"}' | jq -r '.token')

# 2. Get recommendation
curl -X POST http://localhost:8080/api/recommendation \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "soilData": {
      "nitrogen": 90, "phosphorus": 42,
      "potassium": 43, "ph": 6.5, "moisture": 50
    },
    "location": "London"
  }'

πŸ‘₯ Default Users

Created automatically by DataLoader on first run (password: password123):

Email Role Dashboard
admin@crop.com ADMIN Most recommended crops chart
farmer@crop.com FARMER NPK trends + recommendation history
officer@crop.com OFFICER Rainfall & temperature trends

πŸ“Έ Screenshots

Landing Page β€” Modern hero section with feature cards

Dashboard β€” NPK input with validation, recommendation result with confidence bar, trend charts

Login β€” Clean authentication page

Screenshots coming soon β€” run the app to see the full UI!


πŸ—ΊοΈ Roadmap

v1.0.0 β€” βœ… Current Release

  • Core recommendation engine (rule-based)
  • JWT authentication with role-based access
  • Interactive dashboards with Chart.js
  • OpenWeather API integration
  • Modern landing page with feature cards
  • Docker support
  • H2 demo mode

v1.1.0 β€” Planned

  • ML-based recommendation model (scikit-learn / TensorFlow)
  • Crop disease detection module
  • Multi-language support (i18n)
  • Email notifications for recommendations

v2.0.0 β€” Future

  • AI recommendation module with historical data learning
  • Analytics & reporting module
  • Carbon credit tracking
  • Admin panel with user management UI
  • IoT sensor integration (MQTT)
  • Mobile app (React Native / Flutter)

Scalability Path

com.crop/
β”œβ”€β”€ recommendation/    # AI + rule-based engines
β”œβ”€β”€ analytics/         # Reports, trends, exports
β”œβ”€β”€ carbon/            # Carbon credit tracking
β”œβ”€β”€ admin/             # Admin panel controllers
β”œβ”€β”€ notification/      # Email, SMS, push
└── iot/               # Sensor data ingestion

🀝 Contributing

Contributions are welcome! Please read CONTRIBUTING.md for guidelines.


πŸ“„ License

This project is licensed under the MIT License β€” see the LICENSE file for details.


πŸ™ Acknowledgments


Made with ❀️ for smarter agriculture

About

No description, website, or topics provided.

Resources

License

Contributing

Stars

Watchers

Forks

Packages

 
 
 

Contributors