Rajkhanke008 commited on
Commit
e131099
·
verified ·
1 Parent(s): ddbd3d5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +202 -201
app.py CHANGED
@@ -1,201 +1,202 @@
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)
 
 
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=os.getenv('WEATHER_API')
43
+ api_key = api_key
44
+ url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
45
+ try:
46
+ response = requests.get(url)
47
+ response.raise_for_status()
48
+ data = response.json()
49
+ temp = data['main']['temp']
50
+ pressure = data['main']['pressure']
51
+ humidity = data['main']['humidity']
52
+ weather_desc = data['weather'][0]['main']
53
+ return temp, pressure, humidity, weather_desc
54
+ except requests.exceptions.HTTPError:
55
+ return None, None, None, None
56
+
57
+
58
+ # Function to map soil type to pump model's expected format
59
+ def map_soil_to_pump_model(soil_label):
60
+ if soil_label in ['Black Soil', 'Red Soil']:
61
+ return 'DRY'
62
+ elif soil_label == 'Clay Soil':
63
+ return 'WET'
64
+ elif soil_label == 'Alluvial Soil':
65
+ return 'HUMID'
66
+ return None
67
+
68
+
69
+ # Function to run predictions for all soil moisture values
70
+ # Function to run predictions for all soil moisture values
71
+ def run_predictions(crop_type, soil_type_for_pump, region, temperature, pressure, humidity, crop_age, irrigation_type, auto_weather_condition):
72
+ global pump_status, graph_data, previous_pump_status
73
+ pump_status = "Off"
74
+ previous_pump_status = "Off"
75
+ graph_data = []
76
+
77
+ for soil_moisture in soil_moisture_data:
78
+ try:
79
+ soil_moisture_value = float(soil_moisture) # Ensure this is a float
80
+ except ValueError:
81
+ print(f"Skipping invalid soil moisture value: {soil_moisture}")
82
+ continue
83
+
84
+ # Prepare features for pump prediction
85
+ features = np.array([crop_types[crop_type], soil_types[soil_type_for_pump],
86
+ regions[region], temperature if temperature else 0,
87
+ weather_conditions.get(auto_weather_condition, 0),
88
+ pressure if pressure else 0, humidity if humidity else 0,
89
+ int(crop_age), irrigation_types[irrigation_type],
90
+ soil_moisture_value]).reshape(1, -1)
91
+
92
+ # Make the pump prediction
93
+ pump_prediction = pump_model.predict(features)
94
+ pump_status = 'On' if pump_prediction[0] == 1 else 'Off'
95
+ graph_data.append((soil_moisture_value, 1 if pump_status == 'On' else -1)) # Update status to -1 for Off
96
+
97
+ print(f"Predicted Pump Status: {pump_status} for Soil Moisture: {soil_moisture_value}") # Debugging output
98
+
99
+ # Play sound if pump is Off and it wasn't Off previously
100
+ if pump_status == "Off" and previous_pump_status != "Off":
101
+ play_sound()
102
+
103
+ previous_pump_status = pump_status
104
+
105
+ # Wait for 1 second before next prediction
106
+ time.sleep(2)
107
+
108
+
109
+ def play_sound():
110
+ # You can use any sound file here
111
+ print("Beep! Pump is Off.") # Placeholder for actual sound functionality
112
+
113
+
114
+ # Main route
115
+ @app.route('/', methods=['GET', 'POST'])
116
+ def index():
117
+ global soil_moisture_data
118
+
119
+ city = crop_type = region = crop_age = irrigation_type = None
120
+ temperature = pressure = humidity = weather_desc = auto_weather_condition = None
121
+ soil_image_url = None
122
+
123
+ if request.method == 'POST':
124
+ city = request.form.get('city', '')
125
+ crop_type = request.form.get('crop_type', '')
126
+ region = request.form.get('region', '')
127
+ crop_age = request.form.get('crop_age', '')
128
+ irrigation_type = request.form.get('irrigation_type', '')
129
+
130
+ # Handle CSV file upload
131
+ if 'soil_moisture' in request.files:
132
+ soil_moisture_file = request.files['soil_moisture']
133
+ if soil_moisture_file:
134
+ # Read CSV file
135
+ df = pd.read_csv(soil_moisture_file)
136
+ soil_moisture_data = df['Soil Moisture'].tolist()
137
+
138
+ # Handle soil image upload
139
+ soil_image_file = request.files.get('soil_image')
140
+ if soil_image_file:
141
+ # Load and preprocess the image for prediction
142
+ image = Image.open(io.BytesIO(soil_image_file.read()))
143
+ image = image.resize((150, 150))
144
+ image = np.array(image) / 255.0
145
+ if image.shape[-1] == 4:
146
+ image = image[..., :3]
147
+ image = np.expand_dims(image, axis=0)
148
+
149
+ # Predict the soil type
150
+ soil_pred = soil_model.predict(image)
151
+ soil_label = soil_labels[np.argmax(soil_pred)]
152
+ soil_type_for_pump = map_soil_to_pump_model(soil_label)
153
+ else:
154
+ soil_type_for_pump = request.form.get('soil_type')
155
+
156
+ if city:
157
+ temperature, pressure, humidity, weather_desc = get_weather(city)
158
+ auto_weather_condition = "NORMAL" # Default weather condition
159
+ if weather_desc:
160
+ if 'sunny' in weather_desc.lower():
161
+ auto_weather_condition = 'SUNNY'
162
+ elif 'rain' in weather_desc.lower():
163
+ auto_weather_condition = 'RAINY'
164
+ elif 'wind' in weather_desc.lower():
165
+ auto_weather_condition = 'WINDY'
166
+
167
+ if 'predict' in request.form:
168
+ # Start a thread for predictions
169
+ threading.Thread(target=run_predictions, args=(
170
+ crop_type, soil_type_for_pump, region, temperature, pressure, humidity, crop_age, irrigation_type, auto_weather_condition)).start()
171
+ return redirect(url_for('predict'))
172
+
173
+ return render_template('index.html', temperature=temperature, pressure=pressure,
174
+ humidity=humidity, weather_desc=weather_desc, crop_types=crop_types,
175
+ regions=regions, irrigation_types=irrigation_types, soil_types=soil_types,
176
+ crop_type=crop_type, region=region, crop_age=crop_age,
177
+ irrigation_type=irrigation_type, city=city, soil_image_url=soil_image_url)
178
+
179
+
180
+ # Prediction route
181
+ @app.route('/predict', methods=['GET'])
182
+ def predict():
183
+ global pump_status, graph_data
184
+ return render_template('predict.html', pump_status=pump_status, graph_data=graph_data)
185
+
186
+
187
+ # Update graph data every second
188
+ @app.route('/update_graph', methods=['GET'])
189
+ def update_graph():
190
+ global graph_data
191
+ return jsonify(graph_data)
192
+
193
+
194
+ # Update pump status every second
195
+ @app.route('/update_pump_status', methods=['GET'])
196
+ def update_pump_status():
197
+ global pump_status
198
+ return jsonify({'pump_status': pump_status})
199
+
200
+
201
+ if __name__ == '__main__':
202
+ app.run(debug=True)