-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest1.py
355 lines (293 loc) · 11.5 KB
/
test1.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
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
import os
import re
from pathlib import Path
import json
from flask import Flask, request, jsonify, render_template
import google.generativeai as genai
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Flask App Configuration
app = Flask(__name__, static_folder='frontend', template_folder='frontend')
# Gemini API Configuration
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
generation_config = {
"temperature": 0.4,
"top_p": 1,
"top_k": 32,
"max_output_tokens": 4096,
}
safety_settings = [
{"category": f"HARM_CATEGORY_{category}", "threshold": "BLOCK_MEDIUM_AND_ABOVE"}
for category in ["HARASSMENT", "HATE_SPEECH", "SEXUALLY_EXPLICIT", "DANGEROUS_CONTENT"]
]
model = genai.GenerativeModel(
model_name="gemini-1.5-flash",
generation_config=generation_config,
safety_settings=safety_settings,
)
# Utility Functions (Directly copied from original script)
def read_image_data(file_path):
image_path = Path(file_path)
if not image_path.exists():
raise FileNotFoundError(f"Could not find image: {image_path}")
return {"mime_type": "image/jpeg", "data": image_path.read_bytes()}
def clean_response_text(response_text):
clean_text = re.sub(r'[*,]+', '', response_text)
return clean_text
# Core Functions (Directly from original script)
def generate_disease_analysis(image_path, language, district, state, area):
input_prompt = f"""
As a highly skilled plant pathologist, analyze this plant image for a farmer in {area}, {district}, {state}. Please provide:
1. Disease identification (if any)
2. Severity assessment
3. Treatment recommendations
4. Regional context: Is this disease common in {district}? What factors in this region might affect its spread?
5. Preventive measures specific to this geographical area
Consider local climate patterns and common agricultural practices in {state} when making recommendations.
Please be concise and practical in your response.
"""
language_prompt = f"Provide the following response in {language}: {input_prompt}"
image_data = read_image_data(image_path)
response = model.generate_content([language_prompt, image_data])
return clean_response_text(response.text)
def get_regional_disease_insights(district, state, area):
prompt = f"""
As an agricultural expert, provide insights about plant diseases in {area}, {district}, {state}:
1. What are the most common plant diseases in this region?
2. Which seasons are these diseases most prevalent?
3. What are the unique environmental factors in {district} that affect plant health?
4. What preventive measures do you recommend for farmers in this specific area?
Provide a concise, practical response focusing on local relevance.
"""
response = model.generate_content([prompt])
return clean_response_text(response.text)
def get_crop_suggestions(soil_type, ph_level, nutrients, texture, location):
prompt = f"""
As an expert agricultural advisor, based on the following details:
- Soil Type: {soil_type}
- pH Level: {ph_level}
- Nutrient Content: {nutrients}
- Soil Texture: {texture}
- Location: {location}
Suggest the best crops that can be planted in this region and soil type.
Provide reasons for your suggestions, including compatibility with soil, climate, and market demand.
Your response should be concise and farmer-friendly.
"""
response = model.generate_content([prompt])
return response.text.strip()
# Routes
@app.route('/')
def home():
return render_template('index.html')
@app.route('/api/disease-detection', methods=['POST'])
def disease_detection_api():
# Validate and process image upload
if 'image' not in request.files:
return jsonify({"error": "No image uploaded"}), 400
image = request.files['image']
# Collect additional parameters
params = {
'language': request.form.get('language', 'English'),
'district': request.form.get('district', ''),
'state': request.form.get('state', ''),
'area': request.form.get('area', '')
}
# Save temporary image
temp_path = f"/tmp/{image.filename}"
image.save(temp_path)
try:
# Generate analyses
disease_analysis = generate_disease_analysis(
temp_path,
params['language'],
params['district'],
params['state'],
params['area']
)
regional_insights = get_regional_disease_insights(
params['district'],
params['state'],
params['area']
)
return jsonify({
"disease_analysis": disease_analysis,
"regional_insights": regional_insights
})
except Exception as e:
return jsonify({"error": str(e)}), 500
finally:
# Clean up temporary file
if os.path.exists(temp_path):
os.remove(temp_path)
@app.route('/api/crop-recommendation', methods=['POST'])
def crop_recommendation_api():
# Get input data
data = request.json
# Validate inputs
required_fields = ['soil_type', 'ph_level', 'nutrients', 'texture', 'location']
for field in required_fields:
if field not in data:
return jsonify({"error": f"Missing {field}"}), 400
# Generate recommendations
recommendations = get_crop_suggestions(
data['soil_type'],
data['ph_level'],
data['nutrients'],
data['texture'],
data['location']
)
return jsonify({"recommendations": recommendations})
# Error Handling
@app.errorhandler(500)
def handle_500(error):
return jsonify({"error": "Internal Server Error"}), 500
# Main Entry Point
if __name__ == '__main__':
import os
import re
from pathlib import Path
import json
from flask import Flask, request, jsonify, render_template
import google.generativeai as genai
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Flask App Configuration
app = Flask(__name__, static_folder='frontend', template_folder='frontend')
# Gemini API Configuration
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
generation_config = {
"temperature": 0.4,
"top_p": 1,
"top_k": 32,
"max_output_tokens": 4096,
}
safety_settings = [
{"category": f"HARM_CATEGORY_{category}", "threshold": "BLOCK_MEDIUM_AND_ABOVE"}
for category in ["HARASSMENT", "HATE_SPEECH", "SEXUALLY_EXPLICIT", "DANGEROUS_CONTENT"]
]
model = genai.GenerativeModel(
model_name="gemini-1.5-flash",
generation_config=generation_config,
safety_settings=safety_settings,
)
# Utility Functions (Directly copied from original script)
def read_image_data(file_path):
image_path = Path(file_path)
if not image_path.exists():
raise FileNotFoundError(f"Could not find image: {image_path}")
return {"mime_type": "image/jpeg", "data": image_path.read_bytes()}
def clean_response_text(response_text):
clean_text = re.sub(r'[*,]+', '', response_text)
return clean_text
# Core Functions (Directly from original script)
def generate_disease_analysis(image_path, language, district, state, area):
input_prompt = f"""
As a highly skilled plant pathologist, analyze this plant image for a farmer in {area}, {district}, {state}. Please provide:
1. Disease identification (if any)
2. Severity assessment
3. Treatment recommendations
4. Regional context: Is this disease common in {district}? What factors in this region might affect its spread?
5. Preventive measures specific to this geographical area
Consider local climate patterns and common agricultural practices in {state} when making recommendations.
Please be concise and practical in your response.
"""
language_prompt = f"Provide the following response in {language}: {input_prompt}"
image_data = read_image_data(image_path)
response = model.generate_content([language_prompt, image_data])
return clean_response_text(response.text)
def get_regional_disease_insights(district, state, area):
prompt = f"""
As an agricultural expert, provide insights about plant diseases in {area}, {district}, {state}:
1. What are the most common plant diseases in this region?
2. Which seasons are these diseases most prevalent?
3. What are the unique environmental factors in {district} that affect plant health?
4. What preventive measures do you recommend for farmers in this specific area?
Provide a concise, practical response focusing on local relevance.
"""
response = model.generate_content([prompt])
return clean_response_text(response.text)
def get_crop_suggestions(soil_type, ph_level, nutrients, texture, location):
prompt = f"""
As an expert agricultural advisor, based on the following details:
- Soil Type: {soil_type}
- pH Level: {ph_level}
- Nutrient Content: {nutrients}
- Soil Texture: {texture}
- Location: {location}
Suggest the best crops that can be planted in this region and soil type.
Provide reasons for your suggestions, including compatibility with soil, climate, and market demand.
Your response should be concise and farmer-friendly.
"""
response = model.generate_content([prompt])
return response.text.strip()
# Routes
@app.route('/')
def home():
return render_template('index.html')
@app.route('/api/disease-detection', methods=['POST'])
def disease_detection_api():
# Validate and process image upload
if 'image' not in request.files:
return jsonify({"error": "No image uploaded"}), 400
image = request.files['image']
# Collect additional parameters
params = {
'language': request.form.get('language', 'English'),
'district': request.form.get('district', ''),
'state': request.form.get('state', ''),
'area': request.form.get('area', '')
}
# Save temporary image
temp_path = f"/tmp/{image.filename}"
image.save(temp_path)
try:
# Generate analyses
disease_analysis = generate_disease_analysis(
temp_path,
params['language'],
params['district'],
params['state'],
params['area']
)
regional_insights = get_regional_disease_insights(
params['district'],
params['state'],
params['area']
)
return jsonify({
"disease_analysis": disease_analysis,
"regional_insights": regional_insights
})
except Exception as e:
return jsonify({"error": str(e)}), 500
finally:
# Clean up temporary file
if os.path.exists(temp_path):
os.remove(temp_path)
@app.route('/api/crop-recommendation', methods=['POST'])
def crop_recommendation_api():
# Get input data
data = request.json
# Validate inputs
required_fields = ['soil_type', 'ph_level', 'nutrients', 'texture', 'location']
for field in required_fields:
if field not in data:
return jsonify({"error": f"Missing {field}"}), 400
# Generate recommendations
recommendations = get_crop_suggestions(
data['soil_type'],
data['ph_level'],
data['nutrients'],
data['texture'],
data['location']
)
return jsonify({"recommendations": recommendations})
# Error Handling
@app.errorhandler(500)
def handle_500(error):
return jsonify({"error": "Internal Server Error"}), 500
# Main Entry Point
if __name__ == '__main__':
app.run(debug=True)