-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
209 lines (174 loc) · 6.1 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import pandas as pd
from utils.fertilizer import fertilizer_dic
import numpy as np
from flask import Flask, render_template, request, Markup
import requests
import pickle
from flask_mail import Mail, Message
from config import mail_username, mail_password
# ---------
crop_translator = {
'rice' : 'riz',
'maize' : 'maïs',
'chickpea' : 'pois chiche',
'kidneybeans' : 'haricots rénaux',
'pigeonpeas' : "pois d'Angole",
'mothbeans' : 'haricots papillon',
'mungbean' : 'haricot mungo',
'blackgram' : 'mâle',
'lentil' : 'lentille',
'pomegranate' : 'grenade',
'banana' : 'banane',
'mango' : 'mangue',
'grapes' : 'les raisins',
'watermelon' : 'pastèque',
'muskmelon' : 'cantaloup',
'apple' : 'pomme',
'orange' : 'orange',
'papaya' : 'papaye',
'coconut' : 'noix de coco',
'cotton' : 'coton',
'jute' : 'jute',
'coffee' : 'café'
}
inv_crop_translator = {v : k for k, v in crop_translator.items()}
# ---------
def city_name_separater(city_name):
x = city_name.split(' ')
if len(x) != 1:
result = ""
for i in range(len(x)):
result += x[i] + "+"
return result[:-1]
else : return city_name
def weather_fetch(city_name):
city = city_name_separater(city_name)
"""
Fetch and returns the temperature and humidity of a city
:params: city_name
:return: temperature, humidity
"""
api_key = "9d7cde1f6d07ec55650544be1631307e"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
complete_url = base_url + "appid=" + api_key + "&q=" + city
response = requests.get(complete_url)
x = response.json()
if x["cod"] != "404":
y = x["main"]
temperature = round((y["temp"] - 273.15), 2)
humidity = y["humidity"]
return temperature, humidity
else:
return None
crop_recommendation_model_path = 'models/RandomForest.pkl'
crop_recommendation_model = pickle.load(
open(crop_recommendation_model_path, 'rb'))
# ---------
app = Flask(__name__)
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False
app.config["MAIL_USERNAME"] = mail_username
app.config["MAIL_PASSWORD"] = mail_password
mail = Mail(app)
#render Accueil page
@ app.route('/')
def Accueil():
title = 'AIfarm - Accueil'
return render_template('index.html', title=title)
#render Recommandation de culture form page
@ app.route('/culture-recommandation')
def crop_recommendation():
title = 'AIfarm - Recommandation de culture'
return render_template('crops.html', title=title)
#render Recommandation de culture result page
@ app.route('/culture-predire', methods=['POST'])
def crop_prediction():
title = 'AIfarm - Recommandation de culture'
if request.method == 'POST':
N = int(request.form['nitrogen'])
P = int(request.form['phosphorous'])
K = int(request.form['potassium'])
ph = float(request.form['ph'])
rainfall = float(request.form['rainfall'])
city = request.form['city']
if weather_fetch(city) != None:
temperature, humidity = weather_fetch(city)
data = np.array([[N, P, K, temperature, humidity, ph, rainfall]])
my_prediction = crop_recommendation_model.predict(data)
final_prediction = crop_translator[my_prediction[0]]
return render_template('crop_prediction.html', prediction=final_prediction, title=title)
else:
return render_template('try_again.html', title=title)
# --------
#render fertilizer recommendation form page
@app.route('/engrais-recommandation')
def fertilizer_recommendation():
title = 'AIfarm - Engrais recommandatoin'
return render_template('fertilizer.html', title=title)
#render fertilizer results page
@app.route('/engrais-predire', methods=['POST'])
def fert_recommend():
title = 'AIfarm - Engrais recommandation'
crop_name_fr = str(request.form['cropname'])
crop_name = inv_crop_translator[crop_name_fr]
print(crop_name)
N = int(request.form['nitrogen'])
P = int(request.form['phosphorous'])
K = int(request.form['potassium'])
# ph = float(request.form['ph'])
df = pd.read_csv('data/fertilizer.csv')
nr = df[df['Crop'] == crop_name]['N'].iloc[0]
pr = df[df['Crop'] == crop_name]['P'].iloc[0]
kr = df[df['Crop'] == crop_name]['K'].iloc[0]
n = nr - N
p = pr - P
k = kr - K
temp = {abs(n): "N", abs(p): "P", abs(k): "K"}
max_value = temp[max(temp.keys())]
if max(temp) == 0:
key = 'Allgood'
else:
if max_value == "N":
if n < 0:
key = 'NHigh'
else:
key = "Nlow"
elif max_value == "P":
if p < 0:
key = 'PHigh'
else:
key = "Plow"
else:
if k < 0:
key = 'KHigh'
else:
key = "Klow"
response = Markup(str(fertilizer_dic[key]))
return render_template('fertilizer_prediction.html', recommendation=response, title=title)
# --------
#render services page
@app.route('/services')
def services():
title = 'AIfarm - Services'
return render_template('service-page.html', title=title)
# --------
#render contact-us page
@app.route('/contact-us', methods=['GET', 'POST'])
def contact_us():
title = 'AIfarm - contact-us'
if request.method =='POST':
name = str(request.form['name'])
subject = str(request.form['subject'])
email = request.form['email']
message = str(request.form['message'])
msg = Message(subject=f'Mail from {name}', body=f"Nom: {name}\nE-mail: {email}\nObjet: {subject}\n\n\nMessage: {message}", sender=mail_username, recipients=['[email protected]', '[email protected]'] )
print(msg)
mail.send(msg)
return render_template('contact-us.html', success=True)
return render_template('contact-us.html', title=title)
# --------
# --------
if __name__ == '__main__':
app.run(debug=False)