-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
382 lines (296 loc) · 18.9 KB
/
Copy pathapp.py
File metadata and controls
382 lines (296 loc) · 18.9 KB
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
from flask import Flask, render_template, request, send_from_directory, abort, url_for,jsonify
from flask_cors import CORS
from werkzeug.utils import secure_filename
from tensorflow.keras.preprocessing.image import load_img, img_to_array # type: ignore
from keras.models import load_model # type: ignore
import uuid
from werkzeug.utils import secure_filename
import os
import numpy as np
import json
from dotenv import load_dotenv
from markupsafe import Markup
import google.generativeai as genai
import requests
import re
from datetime import datetime
load_dotenv()
app = Flask(__name__)
CORS(app, supports_credentials=True)
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
weather_api_key = os.getenv("WEATHER_API_KEY")
backend_url = os.getenv("backend_url")
imagga_API_KEY = os.getenv("imagga_API_KEY")
geoapify_API_KEY = os.getenv("geoapify_API_KEY")
imagga_SECRET_KEY = os.getenv("imagga_SECRET_KEY")
working_dir = os.path.dirname(os.path.abspath(__file__))
model_path = os.path.join(working_dir, 'trained_model', 'plant_disease_model.h5')
with open(os.path.join(working_dir, 'class_indices.json')) as f:
plant_disease_classes = json.load(f)
model = load_model(model_path)
def get_result(image_path):
img = load_img(image_path, target_size=(224, 224))
x = img_to_array(img)
x = x.astype('float32') / 255.0
x = np.expand_dims(x, axis=0)
predictions = model.predict(x)[0]
predicted_class_index = np.argmax(predictions)
return predicted_class_index
def format_response(response_text):
response_text = response_text.strip()
lines = response_text.split('\n')
cleaned_lines = [line.lstrip('* ').lstrip('# ').replace('**', '').strip() for line in lines]
highlighted_lines = [f"<strong>{line}</strong>" if line.endswith(':') else line for line in cleaned_lines]
return Markup('<br>'.join(highlighted_lines))
def get_weather_info(user_location):
url = f"http://api.weatherapi.com/v1/current.json?key={weather_api_key}&q={user_location}"
response = requests.get(url)
data = response.json()
if 'current' in data:
current = data['current']
return {
'name': data['location']['name'],
'wind_mph': current.get('wind_mph', 'N/A'),
'wind_kph': current.get('wind_kph', 'N/A'),
'temperature': current.get('temp_c', 'N/A'),
'condition': current['condition'].get('text', 'N/A')
}
return {}
def normalize_disease_name(disease_name):
return re.sub(r'_+', ' ', disease_name).strip()
def get_gemini_response(disease_name, weather_info=None):
normalized_disease_name = normalize_disease_name(disease_name)
if 'healthy' in normalized_disease_name.lower():
input_prompt = f"""
Provide detailed information about plant health and care. Include general tips, preventive measures, and recommended practices to maintain plant health. The information should be organized into separate sections, each with a unique ID (e.g., section1, section2, etc.). Do not include a "{normalized_disease_name}" heading at the top; instead, directly present the information as instructed. Use medium-sized headings (such as h3 or h4) with relevant and professional emojis placed before each heading text, ensuring the emojis are appropriate for the content of each heading. Ensure to structure the response with clear sections, each wrapped in an HTML <section> tag with unique html IDs for each sections like section1, section2, etc. Add balanced vertical spacing between elements and list points to enhance readability; the spacing should be consistent and visually appealing, neither too much nor too little, to maintain a clean and organized structure. Highlight key points using the <u> tag to draw attention.
"""
else:
weather_details = ""
if weather_info:
weather_details = f"""
Act as a human expert in plant disease and pest management, covering areas such as fungal diseases, bacterial diseases, viral diseases, nematode diseases, abiotic disorders, and other relevant plant issues. Based on the current weather in {weather_info['name']}, with wind speeds of {weather_info['wind_mph']} mph ({weather_info['wind_kph']} kph) and a temperature of {weather_info['temperature']}°C, explain how these conditions affect the treatment and prevention of the plant/pest disease, including {normalized_disease_name}. Consider whether the current weather is suitable for effective treatment, and provide detailed, actionable advice based on these weather conditions.
Ensure to structure the response with clear sections, each wrapped in an HTML <section> tag with unique html IDs for each sections like section1, section2, etc. Use medium-sized headings (such as <h3> or <h4>) to maintain readability, and include appropriate emojis before the heading text to enhance the content visually. The emojis should be relevant to the content of each heading.
To improve readability, create a spacious layout by adding balanced vertical spacing between elements and list points. The spacing should be consistent, avoiding both excessive and insufficient gaps, to maintain a clean and visually appealing structure. Highlight key points using the <u> tag for emphasis.
"""
input_prompt = f"""
Provide detailed information about the plant/pest disease, including fungal, bacterial, viral, nematode diseases, abiotic disorders, or any other relevant plant/pest issues related to {normalized_disease_name}. The response should cover symptoms, causes, preventive measures, treatment options, and recommended health treatment products. Include {weather_details} to enhance the context. Ensure to structure the response with clear sections, each wrapped in an HTML <section> tag with unique html IDs for each sections like section1, section2, etc. Avoid using "{normalized_disease_name}" as a heading at the top of the response. Directly provide the detailed information following the given instructions, and ensure that each heading ends with a colon. Use medium-sized headings (such as <h3> or <h4>) to maintain a balanced text size. Add a professional and relevant emoji before each heading text based on the heading content, making sure the emoji is appropriate for the subject matter. Additionally, create a spacious layout with balanced vertical spacing between elements and list points to improve readability. Ensure that the spacing is consistent and visually appealing, avoiding both excessive and insufficient gaps. For readability, highlight the main points using the <u> tag.
"""
model = genai.GenerativeModel('gemini-1.5-flash')
response = model.generate_content([input_prompt])
return format_response(response.text)
def check_image_type(file_path):
with open(file_path, 'rb') as image_file:
response = requests.post(
'https://api.imagga.com/v2/tags',
auth=(imagga_API_KEY, imagga_SECRET_KEY),
files={'image': image_file}
)
if response.status_code == 200:
data = response.json()
tags = data['result']['tags'][:5]
is_leaf_or_plant = any(tag['tag']['en'].lower() in ['leaf', 'plant'] for tag in tags)
if is_leaf_or_plant:
return is_leaf_or_plant
else:
return False
else:
return False
def check_auth_and_render(template_if_authenticated, template_if_not_authenticated):
token = request.cookies.get('token')
response = requests.get(f"{backend_url}/api/auth/check", cookies={'token': token})
if template_if_not_authenticated == 'update-password.html':
update_password_token = request.args.get('token')
if update_password_token:
verify_url = f"{backend_url}/api/auth/verify-update-password?token={update_password_token}"
response = requests.get(verify_url)
if response.status_code == 200:
return render_template(template_if_not_authenticated)
else:
return render_template(template_if_authenticated)
else:
return render_template(template_if_authenticated)
else:
if response.status_code == 200:
return render_template(template_if_authenticated)
return render_template(template_if_not_authenticated), 401
@app.route('/uploads/<filename>')
def uploaded_file(filename):
try:
filename = secure_filename(filename)
return send_from_directory(os.path.join(app.root_path, 'uploads'), filename)
except FileNotFoundError:
abort(404)
@app.route('/t&c')
def terms_and_conditions():
return render_template('terms_and_conditions.html')
@app.route('/contact')
def contact():
return render_template('contactus.html')
@app.route('/login', methods=['GET'])
def login():
return check_auth_and_render('index.html', 'login.html')
@app.route('/signup', methods=['GET'])
def signup():
return check_auth_and_render('index.html', 'signup.html')
@app.route('/forgot-password', methods=['GET'])
def forgot_password():
return check_auth_and_render('index.html', 'forgot-password.html')
@app.route('/reset-password', methods=['GET'])
def reset_password():
return check_auth_and_render('404.html', 'update-password.html')
@app.route('/dashboard', methods=['GET'])
def dashboard():
return check_auth_and_render('/dashboard/dashboard.html', 'index.html')
@app.route('/account-settings',methods=['GET'])
def account_settings():
return check_auth_and_render('/dashboard/account-settings.html', 'index.html')
@app.route('/history',methods=['GET'])
def history():
return check_auth_and_render('/dashboard/history.html', 'index.html')
@app.route('/news',methods=['GET'])
def news():
return check_auth_and_render('/dashboard/news.html', 'index.html')
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.route('/get_disease_notify_info', methods=['POST'])
def generate_update():
disease_name = request.json.get('disease')
prompt = f"""Provide brief genral information on "{disease_name}". Include recent developments, changes in disease management practices if avaliable. Format the response in clear sections, with medium-sized headings and relevant emojis for each section. Use clear, well-defined sections with medium-sized headings (e.g., <h3> or <h4>) for each part of the content."""
model = genai.GenerativeModel('gemini-1.5-flash')
response = model.generate_content([prompt])
generated_text = response.text.strip()
return {
'disease_name': disease_name,
'generated_text': generated_text
}
@app.route('/cure', methods=['POST'])
def cure():
data = request.json
cure_percentage = data.get('curePercentage')
cure_level = data.get('cureLevel')
cure_issue_type = data.get('cureIssueType')
disease_name = data.get('diseaseName')
disease_info = data.get('diseaseInfo')
try:
user_location_response = requests.get("https://ipinfo.io/json")
if user_location_response.status_code == 200:
user_location = user_location_response.json().get('loc', '')
else:
user_location = ''
except Exception:
user_location = ''
weather_info = get_weather_info(user_location)
if cure_percentage is not None:
if int(cure_percentage) < 100:
prompt = (f"Hey, regarding {disease_name} ({disease_info}), I've achieved a {cure_percentage}% cure due to {cure_issue_type}. "
f"Could you offer information/guidance based on the provided data and the text I shared to ensure plant recovery? "
f"Current weather: {weather_info}. Please structure the response with clear sections, using medium-sized headings "
f"(like <h3> or <h4>) and appropriate emojis before each heading. Wrap each section in an HTML <section> tag with "
f"unique IDs (e.g., section1, section2) and balanced vertical spacing for readability. Highlight key points using the "
f"<u> tag to draw attention, and ensure the response is concise.")
else:
prompt = (f"Hey, I've successfully cured {disease_name} completely following your advice/guidance ({disease_info}). "
f"Could you provide some tips to keep the plant healthy in the long term? Current weather: {weather_info}. "
f"Please structure the response with clear sections, using medium-sized headings (like <h3> or <h4>) and appropriate "
f"emojis before each heading. Wrap each section in an HTML <section> tag with unique IDs (e.g., section1, section2) "
f"and maintain balanced vertical spacing for readability. Highlight key points using the <u> tag to draw attention, "
f"and ensure the response is concise.")
elif cure_level is not None:
if cure_level != "fully-cure":
prompt = (f"Hey, based on your previous response regarding {disease_name} ({disease_info}), I've reached the {cure_level} "
f"level of cure due to {cure_issue_type}. Could you offer information/guidance based on the provided data and the "
f"text I shared to ensure plant recovery? Current weather: {weather_info}. Please structure the response with clear "
f"sections, using medium-sized headings (like <h3> or <h4>) and appropriate emojis before each heading. Wrap each "
f"section in an HTML <section> tag with unique IDs (e.g., section1, section2) and maintain balanced vertical spacing "
f"for readability. Highlight key points using the <u> tag to draw attention, and ensure the response is concise.")
else:
prompt = (f"Hey, I've fully cured {disease_name} following your advice/guidance ({disease_info}). Please share some tips to "
f"maintain the plant's health. Current weather: {weather_info}. Use medium-sized headings (such as <h3> or <h4>) with "
f"relevant and professional emojis placed before each heading text. Structure the response with clear sections, each "
f"wrapped in an HTML <section> tag with unique HTML IDs for each section like section1, section2, etc. Add balanced "
f"vertical spacing between elements and list points to enhance readability; the spacing should be consistent and visually "
f"appealing. Highlight key points using the <u> tag to draw attention. Ensure the response is concise.")
model = genai.GenerativeModel('gemini-1.5-flash')
response = model.generate_content([prompt])
generated_text = response.text.strip()
return {
'generated_text': generated_text
}
def get_image_urls(predicted_label):
basepath = os.path.dirname(__file__)
images_root_folder = os.path.join(basepath, 'static', 'images', 'crops', predicted_label)
image_urls = []
for root, _, files in os.walk(images_root_folder):
for file in files:
if file.lower().endswith(('.png', '.jpg', '.jpeg')):
relative_path = os.path.relpath(os.path.join(root, file), os.path.join(basepath, 'static'))
relative_path = relative_path.replace('\\', '/')
image_url = url_for('static', filename=relative_path)
image_urls.append(image_url)
return image_urls
@app.route('/', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
f = request.files['file']
user_location_response = requests.get("https://ipinfo.io/json")
if user_location_response.status_code == 200:
data = user_location_response.json()
user_location = data.get('loc', '')
else:
user_location = ''
basepath = os.path.dirname(__file__)
upload_path = os.path.join(basepath, 'uploads')
if not os.path.exists(upload_path):
os.makedirs(upload_path)
unique_filename = f"{uuid.uuid4()}_{secure_filename(f.filename)}"
file_path = os.path.join(upload_path, unique_filename)
f.save(file_path)
if not check_image_type(file_path):
return render_template('index.html', predicted_error="This does not look like a crop.",predicted_label=None, disease_info=None)
predicted_class_index = get_result(file_path)
predicted_label = plant_disease_classes[predicted_class_index]
disease_label = normalize_disease_name(predicted_label)
weather_info = {}
if user_location:
weather_info = get_weather_info(user_location)
disease_info = get_gemini_response(predicted_label, weather_info)
predicted_images_urls = get_image_urls(predicted_label)
data_to_send = {
'file_link': file_path,
'disease_label': disease_label,
'disease_info': disease_info,
'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
token = request.cookies.get('token')
location_data = user_location_response.json()
latitude, longitude = map(float, location_data['loc'].split(','))
url = f'https://api.geoapify.com/v2/places?categories=commercial.garden&filter=circle:{longitude},{latitude},40000&limit=20&apiKey={geoapify_API_KEY}'
shopes_response = requests.get(url)
shopes_data = shopes_response.json()
shopes_dict = {
'shopes': []
}
for feature in shopes_data['features']:
name = feature['properties'].get('name')
address = feature['properties'].get('address_line2')
contact = feature['properties'].get('contact')
if name and address and contact:
shopes_dict['shopes'].append({
'name': name,
'address': address,
'contact': contact
})
check_auth = requests.get(f"{backend_url}/api/auth/check", cookies={'token': token})
if check_auth.status_code == 200:
response = requests.post(f'{backend_url}/api/auth/saveHistory', json=data_to_send, cookies={'token': token})
if response.status_code == 200:
return render_template('index.html', predicted_label=disease_label, disease_info=disease_info,predicted_images_urls=predicted_images_urls,shopes_dict=shopes_dict)
else:
return render_template('index.html', predicted_label=disease_label, disease_info=disease_info,predicted_images_urls=predicted_images_urls,shopes_dict=shopes_dict)
else:
os.remove(file_path)
return render_template('index.html', predicted_label=disease_label, disease_info=disease_info,predicted_images_urls=predicted_images_urls,shopes_dict=shopes_dict)
return render_template('index.html', predicted_label=None, disease_info=None)
if __name__ == '__main__':
app.run(debug=True)