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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, render_template, request, redirect, url_for, jsonify
|
| 2 |
+
from tensorflow.keras.models import load_model
|
| 3 |
+
import numpy as np
|
| 4 |
+
import joblib
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import io
|
| 7 |
+
import requests
|
| 8 |
+
import threading
|
| 9 |
+
import time
|
| 10 |
+
from PIL import Image # Import for image processing
|
| 11 |
+
|
| 12 |
+
app = Flask(__name__)
|
| 13 |
+
|
| 14 |
+
# Load models
|
| 15 |
+
pump_model = joblib.load('pump_status_dt_model.pkl')
|
| 16 |
+
soil_model = load_model('soil_classification_model.h5')
|
| 17 |
+
|
| 18 |
+
# Dictionaries for crop types, regions, etc.
|
| 19 |
+
crop_types = {'BANANA': 0, 'BEAN': 1, 'CABBAGE': 2, 'CITRUS': 3, 'COTTON': 4,
|
| 20 |
+
'MAIZE': 5, 'MELON': 6, 'MUSTARD': 7, 'ONION': 8, 'OTHER': 9,
|
| 21 |
+
'POTATO': 10, 'RICE': 11, 'SOYABEAN': 12, 'SUGARCANE': 13,
|
| 22 |
+
'TOMATO': 14, 'WHEAT': 15}
|
| 23 |
+
|
| 24 |
+
soil_types = {'DRY': 0, 'HUMID': 1, 'WET': 2}
|
| 25 |
+
regions = {'DESERT': 0, 'HUMID': 1, 'SEMI ARID': 2, 'SEMI HUMID': 3}
|
| 26 |
+
weather_conditions = {'SUNNY': 0, 'RAINY': 1, 'WINDY': 2, 'NORMAL': 3}
|
| 27 |
+
irrigation_types = {'Drip Irrigation': 0, 'Manual Irrigation': 1,
|
| 28 |
+
'Sprinkler Irrigation': 2, 'Subsurface Irrigation': 3,
|
| 29 |
+
'Surface Irrigation': 4}
|
| 30 |
+
|
| 31 |
+
soil_labels = {1: 'Black Soil', 2: 'Clay Soil', 0: 'Alluvial Soil', 3: 'Red Soil'}
|
| 32 |
+
|
| 33 |
+
# Global variables
|
| 34 |
+
soil_moisture_data = []
|
| 35 |
+
pump_status = "Off"
|
| 36 |
+
previous_pump_status = "Off"
|
| 37 |
+
graph_data = []
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# Function to fetch weather data
|
| 41 |
+
def get_weather(city):
|
| 42 |
+
api_key = "b3c62ae7f7ad5fc3cb0a7b56cb7cbda6"
|
| 43 |
+
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
|
| 44 |
+
try:
|
| 45 |
+
response = requests.get(url)
|
| 46 |
+
response.raise_for_status()
|
| 47 |
+
data = response.json()
|
| 48 |
+
temp = data['main']['temp']
|
| 49 |
+
pressure = data['main']['pressure']
|
| 50 |
+
humidity = data['main']['humidity']
|
| 51 |
+
weather_desc = data['weather'][0]['main']
|
| 52 |
+
return temp, pressure, humidity, weather_desc
|
| 53 |
+
except requests.exceptions.HTTPError:
|
| 54 |
+
return None, None, None, None
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# Function to map soil type to pump model's expected format
|
| 58 |
+
def map_soil_to_pump_model(soil_label):
|
| 59 |
+
if soil_label in ['Black Soil', 'Red Soil']:
|
| 60 |
+
return 'DRY'
|
| 61 |
+
elif soil_label == 'Clay Soil':
|
| 62 |
+
return 'WET'
|
| 63 |
+
elif soil_label == 'Alluvial Soil':
|
| 64 |
+
return 'HUMID'
|
| 65 |
+
return None
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# Function to run predictions for all soil moisture values
|
| 69 |
+
# Function to run predictions for all soil moisture values
|
| 70 |
+
def run_predictions(crop_type, soil_type_for_pump, region, temperature, pressure, humidity, crop_age, irrigation_type, auto_weather_condition):
|
| 71 |
+
global pump_status, graph_data, previous_pump_status
|
| 72 |
+
pump_status = "Off"
|
| 73 |
+
previous_pump_status = "Off"
|
| 74 |
+
graph_data = []
|
| 75 |
+
|
| 76 |
+
for soil_moisture in soil_moisture_data:
|
| 77 |
+
try:
|
| 78 |
+
soil_moisture_value = float(soil_moisture) # Ensure this is a float
|
| 79 |
+
except ValueError:
|
| 80 |
+
print(f"Skipping invalid soil moisture value: {soil_moisture}")
|
| 81 |
+
continue
|
| 82 |
+
|
| 83 |
+
# Prepare features for pump prediction
|
| 84 |
+
features = np.array([crop_types[crop_type], soil_types[soil_type_for_pump],
|
| 85 |
+
regions[region], temperature if temperature else 0,
|
| 86 |
+
weather_conditions.get(auto_weather_condition, 0),
|
| 87 |
+
pressure if pressure else 0, humidity if humidity else 0,
|
| 88 |
+
int(crop_age), irrigation_types[irrigation_type],
|
| 89 |
+
soil_moisture_value]).reshape(1, -1)
|
| 90 |
+
|
| 91 |
+
# Make the pump prediction
|
| 92 |
+
pump_prediction = pump_model.predict(features)
|
| 93 |
+
pump_status = 'On' if pump_prediction[0] == 1 else 'Off'
|
| 94 |
+
graph_data.append((soil_moisture_value, 1 if pump_status == 'On' else -1)) # Update status to -1 for Off
|
| 95 |
+
|
| 96 |
+
print(f"Predicted Pump Status: {pump_status} for Soil Moisture: {soil_moisture_value}") # Debugging output
|
| 97 |
+
|
| 98 |
+
# Play sound if pump is Off and it wasn't Off previously
|
| 99 |
+
if pump_status == "Off" and previous_pump_status != "Off":
|
| 100 |
+
play_sound()
|
| 101 |
+
|
| 102 |
+
previous_pump_status = pump_status
|
| 103 |
+
|
| 104 |
+
# Wait for 1 second before next prediction
|
| 105 |
+
time.sleep(2)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def play_sound():
|
| 109 |
+
# You can use any sound file here
|
| 110 |
+
print("Beep! Pump is Off.") # Placeholder for actual sound functionality
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# Main route
|
| 114 |
+
@app.route('/', methods=['GET', 'POST'])
|
| 115 |
+
def index():
|
| 116 |
+
global soil_moisture_data
|
| 117 |
+
|
| 118 |
+
city = crop_type = region = crop_age = irrigation_type = None
|
| 119 |
+
temperature = pressure = humidity = weather_desc = auto_weather_condition = None
|
| 120 |
+
soil_image_url = None
|
| 121 |
+
|
| 122 |
+
if request.method == 'POST':
|
| 123 |
+
city = request.form.get('city', '')
|
| 124 |
+
crop_type = request.form.get('crop_type', '')
|
| 125 |
+
region = request.form.get('region', '')
|
| 126 |
+
crop_age = request.form.get('crop_age', '')
|
| 127 |
+
irrigation_type = request.form.get('irrigation_type', '')
|
| 128 |
+
|
| 129 |
+
# Handle CSV file upload
|
| 130 |
+
if 'soil_moisture' in request.files:
|
| 131 |
+
soil_moisture_file = request.files['soil_moisture']
|
| 132 |
+
if soil_moisture_file:
|
| 133 |
+
# Read CSV file
|
| 134 |
+
df = pd.read_csv(soil_moisture_file)
|
| 135 |
+
soil_moisture_data = df['Soil Moisture'].tolist()
|
| 136 |
+
|
| 137 |
+
# Handle soil image upload
|
| 138 |
+
soil_image_file = request.files.get('soil_image')
|
| 139 |
+
if soil_image_file:
|
| 140 |
+
# Load and preprocess the image for prediction
|
| 141 |
+
image = Image.open(io.BytesIO(soil_image_file.read()))
|
| 142 |
+
image = image.resize((150, 150))
|
| 143 |
+
image = np.array(image) / 255.0
|
| 144 |
+
if image.shape[-1] == 4:
|
| 145 |
+
image = image[..., :3]
|
| 146 |
+
image = np.expand_dims(image, axis=0)
|
| 147 |
+
|
| 148 |
+
# Predict the soil type
|
| 149 |
+
soil_pred = soil_model.predict(image)
|
| 150 |
+
soil_label = soil_labels[np.argmax(soil_pred)]
|
| 151 |
+
soil_type_for_pump = map_soil_to_pump_model(soil_label)
|
| 152 |
+
else:
|
| 153 |
+
soil_type_for_pump = request.form.get('soil_type')
|
| 154 |
+
|
| 155 |
+
if city:
|
| 156 |
+
temperature, pressure, humidity, weather_desc = get_weather(city)
|
| 157 |
+
auto_weather_condition = "NORMAL" # Default weather condition
|
| 158 |
+
if weather_desc:
|
| 159 |
+
if 'sunny' in weather_desc.lower():
|
| 160 |
+
auto_weather_condition = 'SUNNY'
|
| 161 |
+
elif 'rain' in weather_desc.lower():
|
| 162 |
+
auto_weather_condition = 'RAINY'
|
| 163 |
+
elif 'wind' in weather_desc.lower():
|
| 164 |
+
auto_weather_condition = 'WINDY'
|
| 165 |
+
|
| 166 |
+
if 'predict' in request.form:
|
| 167 |
+
# Start a thread for predictions
|
| 168 |
+
threading.Thread(target=run_predictions, args=(
|
| 169 |
+
crop_type, soil_type_for_pump, region, temperature, pressure, humidity, crop_age, irrigation_type, auto_weather_condition)).start()
|
| 170 |
+
return redirect(url_for('predict'))
|
| 171 |
+
|
| 172 |
+
return render_template('index.html', temperature=temperature, pressure=pressure,
|
| 173 |
+
humidity=humidity, weather_desc=weather_desc, crop_types=crop_types,
|
| 174 |
+
regions=regions, irrigation_types=irrigation_types, soil_types=soil_types,
|
| 175 |
+
crop_type=crop_type, region=region, crop_age=crop_age,
|
| 176 |
+
irrigation_type=irrigation_type, city=city, soil_image_url=soil_image_url)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# Prediction route
|
| 180 |
+
@app.route('/predict', methods=['GET'])
|
| 181 |
+
def predict():
|
| 182 |
+
global pump_status, graph_data
|
| 183 |
+
return render_template('predict.html', pump_status=pump_status, graph_data=graph_data)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# Update graph data every second
|
| 187 |
+
@app.route('/update_graph', methods=['GET'])
|
| 188 |
+
def update_graph():
|
| 189 |
+
global graph_data
|
| 190 |
+
return jsonify(graph_data)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
# Update pump status every second
|
| 194 |
+
@app.route('/update_pump_status', methods=['GET'])
|
| 195 |
+
def update_pump_status():
|
| 196 |
+
global pump_status
|
| 197 |
+
return jsonify({'pump_status': pump_status})
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
if __name__ == '__main__':
|
| 201 |
+
app.run(debug=True)
|
final_irrigation_data.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pump_status_dt_model.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:63bd7159f70e651ec890fb0ca61bcb4dbbb8b71bb94a079006adf794e887fecb
|
| 3 |
+
size 7641
|
soil_classification_model.h5
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ec920ea24020443d3ad2a5aa228d8f3db0493fcb0ff4384666d1b5c2e8d0a952
|
| 3 |
+
size 57993504
|