Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,339 +1,339 @@
|
|
1 |
-
import requests
|
2 |
-
import json
|
3 |
-
from flask import Flask, render_template, request, jsonify, Response
|
4 |
-
from google import genai
|
5 |
-
import markdown
|
6 |
-
|
7 |
-
app = Flask(__name__)
|
8 |
-
|
9 |
-
# Replace with your actual Gemini API key
|
10 |
-
client = genai.Client(api_key="
|
11 |
-
|
12 |
-
def validate_coordinates(lat, lon):
|
13 |
-
"""Validate and convert latitude and longitude to float."""
|
14 |
-
try:
|
15 |
-
return float(lat), float(lon)
|
16 |
-
except (TypeError, ValueError):
|
17 |
-
return None, None
|
18 |
-
|
19 |
-
@app.route('/')
|
20 |
-
def index():
|
21 |
-
return render_template('index.html')
|
22 |
-
|
23 |
-
@app.route('/get_weather_data', methods=['GET'])
|
24 |
-
def get_weather_data():
|
25 |
-
"""
|
26 |
-
Fetch weather data using Open-Meteo's forecast endpoint:
|
27 |
-
- daily: temperature_2m_max (max_temp), temperature_2m_min (min_temp), precipitation_sum (rain)
|
28 |
-
- hourly: relative_humidity_2m, soil_moisture_3_to_9cm, cloudcover, windspeed_10m
|
29 |
-
- current_weather: for current temperature and wind speed
|
30 |
-
"""
|
31 |
-
lat = request.args.get('lat')
|
32 |
-
lon = request.args.get('lon')
|
33 |
-
lat, lon = validate_coordinates(lat, lon)
|
34 |
-
if lat is None or lon is None:
|
35 |
-
return jsonify({"error": "Invalid coordinates"}), 400
|
36 |
-
|
37 |
-
try:
|
38 |
-
forecast_url = "https://api.open-meteo.com/v1/forecast"
|
39 |
-
forecast_params = {
|
40 |
-
"latitude": lat,
|
41 |
-
"longitude": lon,
|
42 |
-
"current_weather": "true",
|
43 |
-
"daily": "temperature_2m_max,temperature_2m_min,precipitation_sum",
|
44 |
-
"hourly": "relative_humidity_2m,soil_moisture_3_to_9cm,cloudcover,windspeed_10m",
|
45 |
-
"timezone": "auto"
|
46 |
-
}
|
47 |
-
resp = requests.get(forecast_url, params=forecast_params)
|
48 |
-
resp.raise_for_status()
|
49 |
-
data = resp.json()
|
50 |
-
|
51 |
-
daily = data.get("daily", {})
|
52 |
-
hourly = data.get("hourly", {})
|
53 |
-
current = data.get("current_weather", {})
|
54 |
-
|
55 |
-
# Daily data
|
56 |
-
max_temp = daily.get("temperature_2m_max", [None])[0]
|
57 |
-
min_temp = daily.get("temperature_2m_min", [None])[0]
|
58 |
-
rain = daily.get("precipitation_sum", [None])[0]
|
59 |
-
|
60 |
-
# Hourly data (averages)
|
61 |
-
humidity_list = hourly.get("relative_humidity_2m", [])
|
62 |
-
soil_list = hourly.get("soil_moisture_3_to_9cm", [])
|
63 |
-
cloud_list = hourly.get("cloudcover", [])
|
64 |
-
wind_list = hourly.get("windspeed_10m", [])
|
65 |
-
|
66 |
-
avg_humidity = sum(humidity_list)/len(humidity_list) if humidity_list else None
|
67 |
-
avg_soil_moisture = sum(soil_list)/len(soil_list) if soil_list else None
|
68 |
-
avg_cloud_cover = sum(cloud_list)/len(cloud_list) if cloud_list else None
|
69 |
-
|
70 |
-
# Current weather
|
71 |
-
current_temp = current.get("temperature")
|
72 |
-
wind_speed = current.get("windspeed")
|
73 |
-
|
74 |
-
weather = {
|
75 |
-
"max_temp": max_temp,
|
76 |
-
"min_temp": min_temp,
|
77 |
-
"rainfall": rain,
|
78 |
-
"humidity": avg_humidity,
|
79 |
-
"soil_moisture": avg_soil_moisture,
|
80 |
-
"current_temp": current_temp,
|
81 |
-
"wind_speed": wind_speed,
|
82 |
-
"cloud_cover": avg_cloud_cover
|
83 |
-
}
|
84 |
-
return jsonify(weather)
|
85 |
-
except Exception as e:
|
86 |
-
return jsonify({"error": str(e)}), 500
|
87 |
-
|
88 |
-
@app.route('/get_soil_properties', methods=['GET'])
|
89 |
-
def get_soil_properties():
|
90 |
-
"""Fetch soil properties using SoilGrids API and map to user-friendly names."""
|
91 |
-
lat = request.args.get('lat')
|
92 |
-
lon = request.args.get('lon')
|
93 |
-
lat, lon = validate_coordinates(lat, lon)
|
94 |
-
if lat is None or lon is None:
|
95 |
-
return jsonify({"error": "Invalid coordinates"}), 400
|
96 |
-
|
97 |
-
try:
|
98 |
-
prop_url = "https://rest.isric.org/soilgrids/v2.0/properties/query"
|
99 |
-
prop_params = {
|
100 |
-
"lon": str(lon),
|
101 |
-
"lat": str(lat),
|
102 |
-
"property": [
|
103 |
-
"bdod", "cec", "cfvo", "clay", "nitrogen",
|
104 |
-
"ocd", "phh2o", "sand", "silt",
|
105 |
-
"soc", "wv0010", "wv0033", "wv1500"
|
106 |
-
],
|
107 |
-
"depth": "5-15cm",
|
108 |
-
"value": "mean"
|
109 |
-
}
|
110 |
-
headers = {"accept": "application/json"}
|
111 |
-
response = requests.get(prop_url, params=prop_params, headers=headers)
|
112 |
-
response.raise_for_status()
|
113 |
-
prop_data = response.json()
|
114 |
-
|
115 |
-
table_data = []
|
116 |
-
PARAMETER_NAMES = {
|
117 |
-
"bdod": "Bulk Density",
|
118 |
-
"cec": "CEC",
|
119 |
-
"cfvo": "Field Capacity",
|
120 |
-
"clay": "Clay",
|
121 |
-
"nitrogen": "Nitrogen",
|
122 |
-
"ocd": "Organic Carbon Density",
|
123 |
-
"phh2o": "pH",
|
124 |
-
"sand": "Sand",
|
125 |
-
"silt": "Silt",
|
126 |
-
"soc": "Soil Organic Carbon",
|
127 |
-
"wv0010": "Volumetric Water Content (0-10cm)",
|
128 |
-
"wv0033": "Volumetric Water Content (10-33cm)",
|
129 |
-
"wv1500": "Volumetric Water Content (1500)"
|
130 |
-
}
|
131 |
-
for layer in prop_data.get('properties', {}).get('layers', []):
|
132 |
-
parameter = layer.get('name')
|
133 |
-
display_name = PARAMETER_NAMES.get(parameter, parameter)
|
134 |
-
value = layer.get('depths', [{}])[0].get('values', {}).get('mean')
|
135 |
-
if value is None:
|
136 |
-
continue
|
137 |
-
if parameter in ["wv0010", "wv0033", "wv1500"]:
|
138 |
-
final_value = value / 10.0
|
139 |
-
unit = layer.get('unit_measure', {}).get("target_units", "")
|
140 |
-
elif parameter in ["phh2o"]:
|
141 |
-
final_value = value / 10.0
|
142 |
-
unit = layer.get('unit_measure', {}).get("mapped_units", "").replace("*10", "").strip()
|
143 |
-
else:
|
144 |
-
final_value = value
|
145 |
-
unit = layer.get('unit_measure', {}).get("mapped_units", "")
|
146 |
-
table_data.append([display_name, final_value, unit])
|
147 |
-
|
148 |
-
return jsonify({"soil_properties": table_data})
|
149 |
-
except Exception as e:
|
150 |
-
return jsonify({"error": str(e)}), 500
|
151 |
-
|
152 |
-
def call_gemini_api(input_data):
|
153 |
-
"""
|
154 |
-
Enhanced prompt: We request a visually appealing Markdown report WITHOUT
|
155 |
-
showing raw CSS code blocks. Instead, we want a descriptive layout.
|
156 |
-
|
157 |
-
NOTE: We instruct the model to produce headings, paragraphs, and a table
|
158 |
-
in a color-rich, well-spaced manner, but NOT to display raw CSS code.
|
159 |
-
"""
|
160 |
-
prompt = f"""
|
161 |
-
Create a visually appealing, farmer-friendly pest outbreak report in Markdown with the following:
|
162 |
-
|
163 |
-
1. A large, centered heading: "Pest Outbreak Dashboard Report".
|
164 |
-
2. A short paragraph indicating location (latitude: {input_data.get('latitude')}, longitude: {input_data.get('longitude')}), location as per lat,long(like just ex dont consider it as hardoced nagpur,india so kike fetch from lat,long) and the crop/farm context.
|
165 |
-
3. Several subheadings (e.g., "Agricultural Inputs", "Pest Outbreak Analysis", "Best Agricultural Practices", "Insights") with short paragraphs.
|
166 |
-
4. A colorfully styled table (no raw CSS code blocks) with:
|
167 |
-
- Pest Name
|
168 |
-
- Predicted Outbreak Month(s)
|
169 |
-
- Severity
|
170 |
-
- Precautionary Measures
|
171 |
-
5. Provide bullet points for best practices.
|
172 |
-
6. Use a friendly color scheme, with subtle hovers or highlights for rows, and consistent fonts.
|
173 |
-
7. Avoid printing any raw code blocks.
|
174 |
-
8. Incorporate the weather, soil, and agricultural data (like sowing date, irrigation method) into the narrative but do not list them as raw parameters.
|
175 |
-
9. do not give off topic insitruction only pest outbreka report i want okay, and dotn use special characters and justified text
|
176 |
-
Important details from the user:
|
177 |
-
- Crop Type: {input_data.get('crop_type')}
|
178 |
-
- Sowing Date: {input_data.get('sowing_date')}
|
179 |
-
- Harvest Date: {input_data.get('harvest_date')}
|
180 |
-
- Current Growth Stage: {input_data.get('growth_stage')}
|
181 |
-
- Irrigation Frequency: {input_data.get('irrigation_freq')}
|
182 |
-
- Irrigation Method: {input_data.get('irrigation_method')}
|
183 |
-
- Soil Type: {input_data.get('soil_type')}
|
184 |
-
|
185 |
-
- Max Temp: {input_data.get('max_temp')}
|
186 |
-
- Min Temp: {input_data.get('min_temp')}
|
187 |
-
- Current Temp: {input_data.get('current_temp')}
|
188 |
-
- Humidity: {input_data.get('humidity')}
|
189 |
-
- Rainfall: {input_data.get('rain')}
|
190 |
-
- Soil Moisture: {input_data.get('soil_moisture')}
|
191 |
-
- Wind Speed: {input_data.get('wind_speed')}
|
192 |
-
- Cloud Cover: {input_data.get('cloud_cover')}
|
193 |
-
10. also i want specific reocmmendation on pest control (seprate than precuatuonary measure below it in bullet pooints),best agriculktual practices,not generlaized one , but speicifc as perstudiyng each input paprmaetenrindetial okay,poepr sltying tbale should be rendered porpelry etc.. porper bold heaidng ,big fotn,left allgiemnd jsutified text
|
194 |
-
11.again order first title the lat,long,location derive form lat long(ex : nagpur,india) then below it agiruclturla oinput parmeter analysis, then pest tbale then pest avidnaces practice in dpeth 10-12 with bueet pint safter that spciific agrficulturla best practices as per input parameters, after the damage of predicted pest some contnest and more dept contnext this shoudl be order
|
195 |
-
"""
|
196 |
-
response = client.models.generate_content(
|
197 |
-
model="gemini-2.0-flash",
|
198 |
-
contents=prompt,
|
199 |
-
)
|
200 |
-
return response.text
|
201 |
-
|
202 |
-
@app.route('/predict', methods=['POST'])
|
203 |
-
def predict():
|
204 |
-
form_data = request.form.to_dict()
|
205 |
-
report_md = call_gemini_api(form_data)
|
206 |
-
|
207 |
-
# Convert raw markdown to HTML
|
208 |
-
report_html = markdown.markdown(report_md)
|
209 |
-
|
210 |
-
# Inject advanced, colorful styling into the final HTML
|
211 |
-
html_output = f"""<!DOCTYPE html>
|
212 |
-
<html lang="en">
|
213 |
-
<head>
|
214 |
-
<meta charset="UTF-8">
|
215 |
-
<title>Pest Outbreak Dashboard Report</title>
|
216 |
-
<!-- Tailwind for utility classes -->
|
217 |
-
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet">
|
218 |
-
<style>
|
219 |
-
/* Overall page background with a subtle gradient */
|
220 |
-
body {{
|
221 |
-
margin: 0;
|
222 |
-
padding: 2rem;
|
223 |
-
background: linear-gradient(120deg, #f7f7f7 0%, #e3f2fd 100%);
|
224 |
-
font-family: 'Segoe UI', Tahoma, sans-serif;
|
225 |
-
}}
|
226 |
-
|
227 |
-
.report-container {{
|
228 |
-
max-width: 1000px;
|
229 |
-
margin: 0 auto;
|
230 |
-
background-color: #ffffff;
|
231 |
-
border-radius: 8px;
|
232 |
-
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
|
233 |
-
padding: 2rem;
|
234 |
-
transition: transform 0.3s ease, box-shadow 0.3s ease;
|
235 |
-
}}
|
236 |
-
.report-container:hover {{
|
237 |
-
transform: translateY(-4px);
|
238 |
-
box-shadow: 0 12px 24px rgba(0,0,0,0.15);
|
239 |
-
}}
|
240 |
-
|
241 |
-
/* Gradient heading for H1 */
|
242 |
-
.report-container h1 {{
|
243 |
-
text-align: center;
|
244 |
-
font-size: 2rem;
|
245 |
-
margin-bottom: 1.5rem;
|
246 |
-
color: #ffffff;
|
247 |
-
background: linear-gradient(to right, #81c784, #388e3c);
|
248 |
-
padding: 1rem;
|
249 |
-
border-radius: 6px;
|
250 |
-
box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);
|
251 |
-
}}
|
252 |
-
|
253 |
-
/* Secondary headings (H2, H3) */
|
254 |
-
.report-container h2,
|
255 |
-
.report-container h3 {{
|
256 |
-
margin-top: 1.5rem;
|
257 |
-
margin-bottom: 0.75rem;
|
258 |
-
color: #2c3e50;
|
259 |
-
text-align: left;
|
260 |
-
}}
|
261 |
-
|
262 |
-
/* Paragraphs */
|
263 |
-
.report-container p {{
|
264 |
-
margin-bottom: 1rem;
|
265 |
-
color: #555555;
|
266 |
-
text-align: justify;
|
267 |
-
line-height: 1.6;
|
268 |
-
}}
|
269 |
-
|
270 |
-
/* Lists */
|
271 |
-
.report-container ul,
|
272 |
-
.report-container ol {{
|
273 |
-
margin-left: 1.5rem;
|
274 |
-
margin-bottom: 1rem;
|
275 |
-
color: #555555;
|
276 |
-
}}
|
277 |
-
|
278 |
-
/* Table styling */
|
279 |
-
.report-container table {{
|
280 |
-
width: 100%;
|
281 |
-
border-collapse: collapse;
|
282 |
-
margin: 1.5rem 0;
|
283 |
-
}}
|
284 |
-
.report-container thead tr {{
|
285 |
-
background: linear-gradient(to right, #81c784, #388e3c);
|
286 |
-
color: #ffffff;
|
287 |
-
}}
|
288 |
-
.report-container th,
|
289 |
-
.report-container td {{
|
290 |
-
border: 1px solid #ddd;
|
291 |
-
padding: 12px 15px;
|
292 |
-
text-align: left;
|
293 |
-
transition: background-color 0.2s ease;
|
294 |
-
}}
|
295 |
-
.report-container tbody tr:hover {{
|
296 |
-
background-color: #f9f9f9;
|
297 |
-
}}
|
298 |
-
|
299 |
-
/* Responsive table for smaller screens */
|
300 |
-
@media (max-width: 768px) {{
|
301 |
-
.report-container table,
|
302 |
-
.report-container thead,
|
303 |
-
.report-container tbody,
|
304 |
-
.report-container th,
|
305 |
-
.report-container td,
|
306 |
-
.report-container tr {{
|
307 |
-
display: block;
|
308 |
-
width: 100%;
|
309 |
-
}}
|
310 |
-
.report-container thead tr {{
|
311 |
-
display: none;
|
312 |
-
}}
|
313 |
-
.report-container td {{
|
314 |
-
border: none;
|
315 |
-
border-bottom: 1px solid #ddd;
|
316 |
-
position: relative;
|
317 |
-
padding-left: 50%;
|
318 |
-
text-align: left;
|
319 |
-
}}
|
320 |
-
.report-container td:before {{
|
321 |
-
content: attr(data-label);
|
322 |
-
position: absolute;
|
323 |
-
left: 15px;
|
324 |
-
font-weight: bold;
|
325 |
-
}}
|
326 |
-
}}
|
327 |
-
</style>
|
328 |
-
</head>
|
329 |
-
<body>
|
330 |
-
<div class="report-container">
|
331 |
-
{report_html}
|
332 |
-
</div>
|
333 |
-
</body>
|
334 |
-
</html>"""
|
335 |
-
return Response(html_output, mimetype="text/html")
|
336 |
-
|
337 |
-
|
338 |
-
if __name__ == '__main__':
|
339 |
-
app.run(debug=True)
|
|
|
1 |
+
import requests
|
2 |
+
import json
|
3 |
+
from flask import Flask, render_template, request, jsonify, Response
|
4 |
+
from google import genai
|
5 |
+
import markdown
|
6 |
+
|
7 |
+
app = Flask(__name__)
|
8 |
+
|
9 |
+
# Replace with your actual Gemini API key
|
10 |
+
client = genai.Client(api_key="GOOGLE_API_KEY")
|
11 |
+
|
12 |
+
def validate_coordinates(lat, lon):
|
13 |
+
"""Validate and convert latitude and longitude to float."""
|
14 |
+
try:
|
15 |
+
return float(lat), float(lon)
|
16 |
+
except (TypeError, ValueError):
|
17 |
+
return None, None
|
18 |
+
|
19 |
+
@app.route('/')
|
20 |
+
def index():
|
21 |
+
return render_template('index.html')
|
22 |
+
|
23 |
+
@app.route('/get_weather_data', methods=['GET'])
|
24 |
+
def get_weather_data():
|
25 |
+
"""
|
26 |
+
Fetch weather data using Open-Meteo's forecast endpoint:
|
27 |
+
- daily: temperature_2m_max (max_temp), temperature_2m_min (min_temp), precipitation_sum (rain)
|
28 |
+
- hourly: relative_humidity_2m, soil_moisture_3_to_9cm, cloudcover, windspeed_10m
|
29 |
+
- current_weather: for current temperature and wind speed
|
30 |
+
"""
|
31 |
+
lat = request.args.get('lat')
|
32 |
+
lon = request.args.get('lon')
|
33 |
+
lat, lon = validate_coordinates(lat, lon)
|
34 |
+
if lat is None or lon is None:
|
35 |
+
return jsonify({"error": "Invalid coordinates"}), 400
|
36 |
+
|
37 |
+
try:
|
38 |
+
forecast_url = "https://api.open-meteo.com/v1/forecast"
|
39 |
+
forecast_params = {
|
40 |
+
"latitude": lat,
|
41 |
+
"longitude": lon,
|
42 |
+
"current_weather": "true",
|
43 |
+
"daily": "temperature_2m_max,temperature_2m_min,precipitation_sum",
|
44 |
+
"hourly": "relative_humidity_2m,soil_moisture_3_to_9cm,cloudcover,windspeed_10m",
|
45 |
+
"timezone": "auto"
|
46 |
+
}
|
47 |
+
resp = requests.get(forecast_url, params=forecast_params)
|
48 |
+
resp.raise_for_status()
|
49 |
+
data = resp.json()
|
50 |
+
|
51 |
+
daily = data.get("daily", {})
|
52 |
+
hourly = data.get("hourly", {})
|
53 |
+
current = data.get("current_weather", {})
|
54 |
+
|
55 |
+
# Daily data
|
56 |
+
max_temp = daily.get("temperature_2m_max", [None])[0]
|
57 |
+
min_temp = daily.get("temperature_2m_min", [None])[0]
|
58 |
+
rain = daily.get("precipitation_sum", [None])[0]
|
59 |
+
|
60 |
+
# Hourly data (averages)
|
61 |
+
humidity_list = hourly.get("relative_humidity_2m", [])
|
62 |
+
soil_list = hourly.get("soil_moisture_3_to_9cm", [])
|
63 |
+
cloud_list = hourly.get("cloudcover", [])
|
64 |
+
wind_list = hourly.get("windspeed_10m", [])
|
65 |
+
|
66 |
+
avg_humidity = sum(humidity_list)/len(humidity_list) if humidity_list else None
|
67 |
+
avg_soil_moisture = sum(soil_list)/len(soil_list) if soil_list else None
|
68 |
+
avg_cloud_cover = sum(cloud_list)/len(cloud_list) if cloud_list else None
|
69 |
+
|
70 |
+
# Current weather
|
71 |
+
current_temp = current.get("temperature")
|
72 |
+
wind_speed = current.get("windspeed")
|
73 |
+
|
74 |
+
weather = {
|
75 |
+
"max_temp": max_temp,
|
76 |
+
"min_temp": min_temp,
|
77 |
+
"rainfall": rain,
|
78 |
+
"humidity": avg_humidity,
|
79 |
+
"soil_moisture": avg_soil_moisture,
|
80 |
+
"current_temp": current_temp,
|
81 |
+
"wind_speed": wind_speed,
|
82 |
+
"cloud_cover": avg_cloud_cover
|
83 |
+
}
|
84 |
+
return jsonify(weather)
|
85 |
+
except Exception as e:
|
86 |
+
return jsonify({"error": str(e)}), 500
|
87 |
+
|
88 |
+
@app.route('/get_soil_properties', methods=['GET'])
|
89 |
+
def get_soil_properties():
|
90 |
+
"""Fetch soil properties using SoilGrids API and map to user-friendly names."""
|
91 |
+
lat = request.args.get('lat')
|
92 |
+
lon = request.args.get('lon')
|
93 |
+
lat, lon = validate_coordinates(lat, lon)
|
94 |
+
if lat is None or lon is None:
|
95 |
+
return jsonify({"error": "Invalid coordinates"}), 400
|
96 |
+
|
97 |
+
try:
|
98 |
+
prop_url = "https://rest.isric.org/soilgrids/v2.0/properties/query"
|
99 |
+
prop_params = {
|
100 |
+
"lon": str(lon),
|
101 |
+
"lat": str(lat),
|
102 |
+
"property": [
|
103 |
+
"bdod", "cec", "cfvo", "clay", "nitrogen",
|
104 |
+
"ocd", "phh2o", "sand", "silt",
|
105 |
+
"soc", "wv0010", "wv0033", "wv1500"
|
106 |
+
],
|
107 |
+
"depth": "5-15cm",
|
108 |
+
"value": "mean"
|
109 |
+
}
|
110 |
+
headers = {"accept": "application/json"}
|
111 |
+
response = requests.get(prop_url, params=prop_params, headers=headers)
|
112 |
+
response.raise_for_status()
|
113 |
+
prop_data = response.json()
|
114 |
+
|
115 |
+
table_data = []
|
116 |
+
PARAMETER_NAMES = {
|
117 |
+
"bdod": "Bulk Density",
|
118 |
+
"cec": "CEC",
|
119 |
+
"cfvo": "Field Capacity",
|
120 |
+
"clay": "Clay",
|
121 |
+
"nitrogen": "Nitrogen",
|
122 |
+
"ocd": "Organic Carbon Density",
|
123 |
+
"phh2o": "pH",
|
124 |
+
"sand": "Sand",
|
125 |
+
"silt": "Silt",
|
126 |
+
"soc": "Soil Organic Carbon",
|
127 |
+
"wv0010": "Volumetric Water Content (0-10cm)",
|
128 |
+
"wv0033": "Volumetric Water Content (10-33cm)",
|
129 |
+
"wv1500": "Volumetric Water Content (1500)"
|
130 |
+
}
|
131 |
+
for layer in prop_data.get('properties', {}).get('layers', []):
|
132 |
+
parameter = layer.get('name')
|
133 |
+
display_name = PARAMETER_NAMES.get(parameter, parameter)
|
134 |
+
value = layer.get('depths', [{}])[0].get('values', {}).get('mean')
|
135 |
+
if value is None:
|
136 |
+
continue
|
137 |
+
if parameter in ["wv0010", "wv0033", "wv1500"]:
|
138 |
+
final_value = value / 10.0
|
139 |
+
unit = layer.get('unit_measure', {}).get("target_units", "")
|
140 |
+
elif parameter in ["phh2o"]:
|
141 |
+
final_value = value / 10.0
|
142 |
+
unit = layer.get('unit_measure', {}).get("mapped_units", "").replace("*10", "").strip()
|
143 |
+
else:
|
144 |
+
final_value = value
|
145 |
+
unit = layer.get('unit_measure', {}).get("mapped_units", "")
|
146 |
+
table_data.append([display_name, final_value, unit])
|
147 |
+
|
148 |
+
return jsonify({"soil_properties": table_data})
|
149 |
+
except Exception as e:
|
150 |
+
return jsonify({"error": str(e)}), 500
|
151 |
+
|
152 |
+
def call_gemini_api(input_data):
|
153 |
+
"""
|
154 |
+
Enhanced prompt: We request a visually appealing Markdown report WITHOUT
|
155 |
+
showing raw CSS code blocks. Instead, we want a descriptive layout.
|
156 |
+
|
157 |
+
NOTE: We instruct the model to produce headings, paragraphs, and a table
|
158 |
+
in a color-rich, well-spaced manner, but NOT to display raw CSS code.
|
159 |
+
"""
|
160 |
+
prompt = f"""
|
161 |
+
Create a visually appealing, farmer-friendly pest outbreak report in Markdown with the following:
|
162 |
+
|
163 |
+
1. A large, centered heading: "Pest Outbreak Dashboard Report".
|
164 |
+
2. A short paragraph indicating location (latitude: {input_data.get('latitude')}, longitude: {input_data.get('longitude')}), location as per lat,long(like just ex dont consider it as hardoced nagpur,india so kike fetch from lat,long) and the crop/farm context.
|
165 |
+
3. Several subheadings (e.g., "Agricultural Inputs", "Pest Outbreak Analysis", "Best Agricultural Practices", "Insights") with short paragraphs.
|
166 |
+
4. A colorfully styled table (no raw CSS code blocks) with:
|
167 |
+
- Pest Name
|
168 |
+
- Predicted Outbreak Month(s)
|
169 |
+
- Severity
|
170 |
+
- Precautionary Measures
|
171 |
+
5. Provide bullet points for best practices.
|
172 |
+
6. Use a friendly color scheme, with subtle hovers or highlights for rows, and consistent fonts.
|
173 |
+
7. Avoid printing any raw code blocks.
|
174 |
+
8. Incorporate the weather, soil, and agricultural data (like sowing date, irrigation method) into the narrative but do not list them as raw parameters.
|
175 |
+
9. do not give off topic insitruction only pest outbreka report i want okay, and dotn use special characters and justified text
|
176 |
+
Important details from the user:
|
177 |
+
- Crop Type: {input_data.get('crop_type')}
|
178 |
+
- Sowing Date: {input_data.get('sowing_date')}
|
179 |
+
- Harvest Date: {input_data.get('harvest_date')}
|
180 |
+
- Current Growth Stage: {input_data.get('growth_stage')}
|
181 |
+
- Irrigation Frequency: {input_data.get('irrigation_freq')}
|
182 |
+
- Irrigation Method: {input_data.get('irrigation_method')}
|
183 |
+
- Soil Type: {input_data.get('soil_type')}
|
184 |
+
|
185 |
+
- Max Temp: {input_data.get('max_temp')}
|
186 |
+
- Min Temp: {input_data.get('min_temp')}
|
187 |
+
- Current Temp: {input_data.get('current_temp')}
|
188 |
+
- Humidity: {input_data.get('humidity')}
|
189 |
+
- Rainfall: {input_data.get('rain')}
|
190 |
+
- Soil Moisture: {input_data.get('soil_moisture')}
|
191 |
+
- Wind Speed: {input_data.get('wind_speed')}
|
192 |
+
- Cloud Cover: {input_data.get('cloud_cover')}
|
193 |
+
10. also i want specific reocmmendation on pest control (seprate than precuatuonary measure below it in bullet pooints),best agriculktual practices,not generlaized one , but speicifc as perstudiyng each input paprmaetenrindetial okay,poepr sltying tbale should be rendered porpelry etc.. porper bold heaidng ,big fotn,left allgiemnd jsutified text
|
194 |
+
11.again order first title the lat,long,location derive form lat long(ex : nagpur,india) then below it agiruclturla oinput parmeter analysis, then pest tbale then pest avidnaces practice in dpeth 10-12 with bueet pint safter that spciific agrficulturla best practices as per input parameters, after the damage of predicted pest some contnest and more dept contnext this shoudl be order
|
195 |
+
"""
|
196 |
+
response = client.models.generate_content(
|
197 |
+
model="gemini-2.0-flash",
|
198 |
+
contents=prompt,
|
199 |
+
)
|
200 |
+
return response.text
|
201 |
+
|
202 |
+
@app.route('/predict', methods=['POST'])
|
203 |
+
def predict():
|
204 |
+
form_data = request.form.to_dict()
|
205 |
+
report_md = call_gemini_api(form_data)
|
206 |
+
|
207 |
+
# Convert raw markdown to HTML
|
208 |
+
report_html = markdown.markdown(report_md)
|
209 |
+
|
210 |
+
# Inject advanced, colorful styling into the final HTML
|
211 |
+
html_output = f"""<!DOCTYPE html>
|
212 |
+
<html lang="en">
|
213 |
+
<head>
|
214 |
+
<meta charset="UTF-8">
|
215 |
+
<title>Pest Outbreak Dashboard Report</title>
|
216 |
+
<!-- Tailwind for utility classes -->
|
217 |
+
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet">
|
218 |
+
<style>
|
219 |
+
/* Overall page background with a subtle gradient */
|
220 |
+
body {{
|
221 |
+
margin: 0;
|
222 |
+
padding: 2rem;
|
223 |
+
background: linear-gradient(120deg, #f7f7f7 0%, #e3f2fd 100%);
|
224 |
+
font-family: 'Segoe UI', Tahoma, sans-serif;
|
225 |
+
}}
|
226 |
+
|
227 |
+
.report-container {{
|
228 |
+
max-width: 1000px;
|
229 |
+
margin: 0 auto;
|
230 |
+
background-color: #ffffff;
|
231 |
+
border-radius: 8px;
|
232 |
+
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
|
233 |
+
padding: 2rem;
|
234 |
+
transition: transform 0.3s ease, box-shadow 0.3s ease;
|
235 |
+
}}
|
236 |
+
.report-container:hover {{
|
237 |
+
transform: translateY(-4px);
|
238 |
+
box-shadow: 0 12px 24px rgba(0,0,0,0.15);
|
239 |
+
}}
|
240 |
+
|
241 |
+
/* Gradient heading for H1 */
|
242 |
+
.report-container h1 {{
|
243 |
+
text-align: center;
|
244 |
+
font-size: 2rem;
|
245 |
+
margin-bottom: 1.5rem;
|
246 |
+
color: #ffffff;
|
247 |
+
background: linear-gradient(to right, #81c784, #388e3c);
|
248 |
+
padding: 1rem;
|
249 |
+
border-radius: 6px;
|
250 |
+
box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);
|
251 |
+
}}
|
252 |
+
|
253 |
+
/* Secondary headings (H2, H3) */
|
254 |
+
.report-container h2,
|
255 |
+
.report-container h3 {{
|
256 |
+
margin-top: 1.5rem;
|
257 |
+
margin-bottom: 0.75rem;
|
258 |
+
color: #2c3e50;
|
259 |
+
text-align: left;
|
260 |
+
}}
|
261 |
+
|
262 |
+
/* Paragraphs */
|
263 |
+
.report-container p {{
|
264 |
+
margin-bottom: 1rem;
|
265 |
+
color: #555555;
|
266 |
+
text-align: justify;
|
267 |
+
line-height: 1.6;
|
268 |
+
}}
|
269 |
+
|
270 |
+
/* Lists */
|
271 |
+
.report-container ul,
|
272 |
+
.report-container ol {{
|
273 |
+
margin-left: 1.5rem;
|
274 |
+
margin-bottom: 1rem;
|
275 |
+
color: #555555;
|
276 |
+
}}
|
277 |
+
|
278 |
+
/* Table styling */
|
279 |
+
.report-container table {{
|
280 |
+
width: 100%;
|
281 |
+
border-collapse: collapse;
|
282 |
+
margin: 1.5rem 0;
|
283 |
+
}}
|
284 |
+
.report-container thead tr {{
|
285 |
+
background: linear-gradient(to right, #81c784, #388e3c);
|
286 |
+
color: #ffffff;
|
287 |
+
}}
|
288 |
+
.report-container th,
|
289 |
+
.report-container td {{
|
290 |
+
border: 1px solid #ddd;
|
291 |
+
padding: 12px 15px;
|
292 |
+
text-align: left;
|
293 |
+
transition: background-color 0.2s ease;
|
294 |
+
}}
|
295 |
+
.report-container tbody tr:hover {{
|
296 |
+
background-color: #f9f9f9;
|
297 |
+
}}
|
298 |
+
|
299 |
+
/* Responsive table for smaller screens */
|
300 |
+
@media (max-width: 768px) {{
|
301 |
+
.report-container table,
|
302 |
+
.report-container thead,
|
303 |
+
.report-container tbody,
|
304 |
+
.report-container th,
|
305 |
+
.report-container td,
|
306 |
+
.report-container tr {{
|
307 |
+
display: block;
|
308 |
+
width: 100%;
|
309 |
+
}}
|
310 |
+
.report-container thead tr {{
|
311 |
+
display: none;
|
312 |
+
}}
|
313 |
+
.report-container td {{
|
314 |
+
border: none;
|
315 |
+
border-bottom: 1px solid #ddd;
|
316 |
+
position: relative;
|
317 |
+
padding-left: 50%;
|
318 |
+
text-align: left;
|
319 |
+
}}
|
320 |
+
.report-container td:before {{
|
321 |
+
content: attr(data-label);
|
322 |
+
position: absolute;
|
323 |
+
left: 15px;
|
324 |
+
font-weight: bold;
|
325 |
+
}}
|
326 |
+
}}
|
327 |
+
</style>
|
328 |
+
</head>
|
329 |
+
<body>
|
330 |
+
<div class="report-container">
|
331 |
+
{report_html}
|
332 |
+
</div>
|
333 |
+
</body>
|
334 |
+
</html>"""
|
335 |
+
return Response(html_output, mimetype="text/html")
|
336 |
+
|
337 |
+
|
338 |
+
if __name__ == '__main__':
|
339 |
+
app.run(debug=True)
|