rajkhanke commited on
Commit
210b29f
·
verified ·
1 Parent(s): a2b79e3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -42
app.py CHANGED
@@ -11,6 +11,7 @@ api_key = os.getenv('GEMINI_API_KEY')
11
  # Replace with your actual Gemini API key
12
  client = genai.Client(api_key=api_key)
13
 
 
14
  def validate_coordinates(lat, lon):
15
  """Validate and convert latitude and longitude to float."""
16
  try:
@@ -46,7 +47,7 @@ def get_weather_data():
46
  "hourly": "relative_humidity_2m,soil_moisture_3_to_9cm,cloudcover,windspeed_10m",
47
  "timezone": "auto"
48
  }
49
- resp = requests.get(forecast_url, params=forecast_params, timeout=10)
50
  resp.raise_for_status()
51
  data = resp.json()
52
 
@@ -98,18 +99,19 @@ def get_soil_properties():
98
 
99
  try:
100
  prop_url = "https://rest.isric.org/soilgrids/v2.0/properties/query"
101
- # It's often better to send the list of properties as a comma-separated string.
102
- properties = "bdod,cec,cfvo,clay,nitrogen,ocd,phh2o,sand,silt,soc,wv0010,wv0033,wv1500"
103
  prop_params = {
104
  "lon": str(lon),
105
  "lat": str(lat),
106
- "property": properties,
 
 
 
 
107
  "depth": "5-15cm",
108
  "value": "mean"
109
  }
110
  headers = {"accept": "application/json"}
111
- # Add timeout to avoid hanging (10 seconds in this example)
112
- response = requests.get(prop_url, params=prop_params, headers=headers, timeout=10)
113
  response.raise_for_status()
114
  prop_data = response.json()
115
 
@@ -151,49 +153,48 @@ def get_soil_properties():
151
  return jsonify({"error": str(e)}), 500
152
 
153
  def call_gemini_api(input_data):
154
- language = input_data.get('language', 'English')
 
 
 
 
 
 
155
  prompt = f"""
156
  Create a visually appealing, farmer-friendly pest outbreak report in Markdown with the following:
 
157
  1. A large, centered heading: "Pest Outbreak Dashboard Report".
158
- 2. A short paragraph indicating location (latitude: {input_data.get('latitude')}, longitude: {input_data.get('longitude')}) with the location derived from lat,long.
159
  3. Several subheadings (e.g., "Agricultural Inputs", "Pest Outbreak Analysis", "Best Agricultural Practices", "Insights") with short paragraphs.
160
  4. A colorfully styled table (no raw CSS code blocks) with:
161
  - Pest Name
162
  - Predicted Outbreak Month(s)
163
  - Severity
164
- - Potential Damage by Pests
165
- - Precautionary Measures against damages
166
- 5. Provide bullet points for best practices.
167
- 6. Use a friendly color scheme with subtle hovers or highlights for rows, and consistent fonts.
168
- 7. Avoid printing any raw code blocks.
169
- 8. Incorporate the weather, soil, and agricultural data (like sowing date, irrigation method) into the narrative without listing them as raw parameters.
170
- 9. Do not give off-topic instructions—only pest outbreak report instructions.
171
- 10. Important details from the user:
172
- - Crop Type: {input_data.get('crop_type')}
173
- - Sowing Date: {input_data.get('sowing_date')}
174
- - Harvest Date: {input_data.get('harvest_date')}
175
- - Current Growth Stage: {input_data.get('growth_stage')}
176
- - Irrigation Frequency: {input_data.get('irrigation_freq')}
177
- - Irrigation Method: {input_data.get('irrigation_method')}
178
- - Soil Type: {input_data.get('soil_type')}
179
- - Max Temp: {input_data.get('max_temp')}
180
- - Min Temp: {input_data.get('min_temp')}
181
- - Current Temp: {input_data.get('current_temp')}
182
- - Humidity: {input_data.get('humidity')}
183
- - Rainfall: {input_data.get('rain')}
184
- - Soil Moisture: {input_data.get('soil_moisture')}
185
- - Wind Speed: {input_data.get('wind_speed')}
186
- - Cloud Cover: {input_data.get('cloud_cover')}
187
- 11. Order the content as follows:
188
- - First, display the title along with the derived location (e.g., Nagpur, India).
189
- - Next, show the agricultural input parameters analysis.
190
- - Then, present the pest table.
191
- - Followed by pest avoidance practices in-depth (5-6 bullet points).
192
- - Finally, include specific agricultural best practices based on the inputs.
193
- 12. Use short, easily understandable sentences suitable for farmers, with large fonts and colorful subheadings.
194
- 13. Do not include long paragraphs; keep the language simple and the report well-formatted.
195
- 14. Highlight important points (such as key damages, recommendations, pest names, key seasons) with yellow highlighters (only highlight key points, not the text).
196
- Please provide the complete report in {language} language only.
197
  """
198
  response = client.models.generate_content(
199
  model="gemini-2.0-flash",
@@ -225,6 +226,7 @@ def predict():
225
  background: linear-gradient(120deg, #f7f7f7 0%, #e3f2fd 100%);
226
  font-family: 'Segoe UI', Tahoma, sans-serif;
227
  }}
 
228
  .report-container {{
229
  max-width: 1000px;
230
  margin: 0 auto;
@@ -238,6 +240,7 @@ def predict():
238
  transform: translateY(-4px);
239
  box-shadow: 0 12px 24px rgba(0,0,0,0.15);
240
  }}
 
241
  /* Gradient heading for H1 */
242
  .report-container h1 {{
243
  text-align: center;
@@ -249,6 +252,7 @@ def predict():
249
  border-radius: 6px;
250
  box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);
251
  }}
 
252
  /* Secondary headings (H2, H3) */
253
  .report-container h2,
254
  .report-container h3 {{
@@ -257,6 +261,7 @@ def predict():
257
  color: #2c3e50;
258
  text-align: left;
259
  }}
 
260
  /* Paragraphs */
261
  .report-container p {{
262
  margin-bottom: 1rem;
@@ -264,6 +269,7 @@ def predict():
264
  text-align: justify;
265
  line-height: 1.6;
266
  }}
 
267
  /* Lists */
268
  .report-container ul,
269
  .report-container ol {{
@@ -271,6 +277,7 @@ def predict():
271
  margin-bottom: 1rem;
272
  color: #555555;
273
  }}
 
274
  /* Table styling */
275
  .report-container table {{
276
  width: 100%;
@@ -291,6 +298,7 @@ def predict():
291
  .report-container tbody tr:hover {{
292
  background-color: #f9f9f9;
293
  }}
 
294
  /* Responsive table for smaller screens */
295
  @media (max-width: 768px) {{
296
  .report-container table,
@@ -329,5 +337,6 @@ def predict():
329
  </html>"""
330
  return Response(html_output, mimetype="text/html")
331
 
 
332
  if __name__ == '__main__':
333
- app.run(debug=True)
 
11
  # Replace with your actual Gemini API key
12
  client = genai.Client(api_key=api_key)
13
 
14
+
15
  def validate_coordinates(lat, lon):
16
  """Validate and convert latitude and longitude to float."""
17
  try:
 
47
  "hourly": "relative_humidity_2m,soil_moisture_3_to_9cm,cloudcover,windspeed_10m",
48
  "timezone": "auto"
49
  }
50
+ resp = requests.get(forecast_url, params=forecast_params)
51
  resp.raise_for_status()
52
  data = resp.json()
53
 
 
99
 
100
  try:
101
  prop_url = "https://rest.isric.org/soilgrids/v2.0/properties/query"
 
 
102
  prop_params = {
103
  "lon": str(lon),
104
  "lat": str(lat),
105
+ "property": [
106
+ "bdod", "cec", "cfvo", "clay", "nitrogen",
107
+ "ocd", "phh2o", "sand", "silt",
108
+ "soc", "wv0010", "wv0033", "wv1500"
109
+ ],
110
  "depth": "5-15cm",
111
  "value": "mean"
112
  }
113
  headers = {"accept": "application/json"}
114
+ response = requests.get(prop_url, params=prop_params, headers=headers)
 
115
  response.raise_for_status()
116
  prop_data = response.json()
117
 
 
153
  return jsonify({"error": str(e)}), 500
154
 
155
  def call_gemini_api(input_data):
156
+ """
157
+ Enhanced prompt: We request a visually appealing Markdown report WITHOUT
158
+ showing raw CSS code blocks. Instead, we want a descriptive layout.
159
+
160
+ NOTE: We instruct the model to produce headings, paragraphs, and a table
161
+ in a color-rich, well-spaced manner, but NOT to display raw CSS code.
162
+ """
163
  prompt = f"""
164
  Create a visually appealing, farmer-friendly pest outbreak report in Markdown with the following:
165
+
166
  1. A large, centered heading: "Pest Outbreak Dashboard Report".
167
+ 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.
168
  3. Several subheadings (e.g., "Agricultural Inputs", "Pest Outbreak Analysis", "Best Agricultural Practices", "Insights") with short paragraphs.
169
  4. A colorfully styled table (no raw CSS code blocks) with:
170
  - Pest Name
171
  - Predicted Outbreak Month(s)
172
  - Severity
173
+ - Precautionary Measures
174
+ 5. Provide bullet points for best practices.
175
+ 6. Use a friendly color scheme, with subtle hovers or highlights for rows, and consistent fonts.
176
+ 7. Avoid printing any raw code blocks.
177
+ 8. Incorporate the weather, soil, and agricultural data (like sowing date, irrigation method) into the narrative but do not list them as raw parameters.
178
+ 9. do not give off topic insitruction only pest outbreka report i want okay, and dotn use special characters and justified text
179
+ Important details from the user:
180
+ - Crop Type: {input_data.get('crop_type')}
181
+ - Sowing Date: {input_data.get('sowing_date')}
182
+ - Harvest Date: {input_data.get('harvest_date')}
183
+ - Current Growth Stage: {input_data.get('growth_stage')}
184
+ - Irrigation Frequency: {input_data.get('irrigation_freq')}
185
+ - Irrigation Method: {input_data.get('irrigation_method')}
186
+ - Soil Type: {input_data.get('soil_type')}
187
+
188
+ - Max Temp: {input_data.get('max_temp')}
189
+ - Min Temp: {input_data.get('min_temp')}
190
+ - Current Temp: {input_data.get('current_temp')}
191
+ - Humidity: {input_data.get('humidity')}
192
+ - Rainfall: {input_data.get('rain')}
193
+ - Soil Moisture: {input_data.get('soil_moisture')}
194
+ - Wind Speed: {input_data.get('wind_speed')}
195
+ - Cloud Cover: {input_data.get('cloud_cover')}
196
+ 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
197
+ 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
 
 
 
 
 
 
 
 
198
  """
199
  response = client.models.generate_content(
200
  model="gemini-2.0-flash",
 
226
  background: linear-gradient(120deg, #f7f7f7 0%, #e3f2fd 100%);
227
  font-family: 'Segoe UI', Tahoma, sans-serif;
228
  }}
229
+
230
  .report-container {{
231
  max-width: 1000px;
232
  margin: 0 auto;
 
240
  transform: translateY(-4px);
241
  box-shadow: 0 12px 24px rgba(0,0,0,0.15);
242
  }}
243
+
244
  /* Gradient heading for H1 */
245
  .report-container h1 {{
246
  text-align: center;
 
252
  border-radius: 6px;
253
  box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);
254
  }}
255
+
256
  /* Secondary headings (H2, H3) */
257
  .report-container h2,
258
  .report-container h3 {{
 
261
  color: #2c3e50;
262
  text-align: left;
263
  }}
264
+
265
  /* Paragraphs */
266
  .report-container p {{
267
  margin-bottom: 1rem;
 
269
  text-align: justify;
270
  line-height: 1.6;
271
  }}
272
+
273
  /* Lists */
274
  .report-container ul,
275
  .report-container ol {{
 
277
  margin-bottom: 1rem;
278
  color: #555555;
279
  }}
280
+
281
  /* Table styling */
282
  .report-container table {{
283
  width: 100%;
 
298
  .report-container tbody tr:hover {{
299
  background-color: #f9f9f9;
300
  }}
301
+
302
  /* Responsive table for smaller screens */
303
  @media (max-width: 768px) {{
304
  .report-container table,
 
337
  </html>"""
338
  return Response(html_output, mimetype="text/html")
339
 
340
+
341
  if __name__ == '__main__':
342
+ app.run(debug=True)