rajkhanke commited on
Commit
2fede66
·
verified ·
1 Parent(s): 757ec5b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -48
app.py CHANGED
@@ -11,11 +11,19 @@ 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
 
15
  @app.route('/')
16
  def index():
17
  return render_template('index.html')
18
 
 
19
  @app.route('/get_weather_data', methods=['GET'])
20
  def get_weather_data():
21
  """
@@ -40,8 +48,7 @@ def get_weather_data():
40
  "hourly": "relative_humidity_2m,soil_moisture_3_to_9cm,cloudcover,windspeed_10m",
41
  "timezone": "auto"
42
  }
43
- # Added timeout to prevent hanging indefinitely
44
- resp = requests.get(forecast_url, params=forecast_params, timeout=10)
45
  resp.raise_for_status()
46
  data = resp.json()
47
 
@@ -83,32 +90,9 @@ def get_weather_data():
83
  return jsonify({"error": str(e)}), 500
84
 
85
 
86
- def validate_coordinates(lat, lon):
87
- """Convert and validate latitude and longitude values."""
88
- try:
89
- return float(lat), float(lon)
90
- except (TypeError, ValueError):
91
- return None, None
92
-
93
- # Mapping of soil property short codes to user-friendly names
94
- PARAMETER_NAMES = {
95
- "bdod": "Bulk Density",
96
- "cec": "CEC",
97
- "cfvo": "Field Capacity",
98
- "clay": "Clay Content",
99
- "nitrogen": "Nitrogen",
100
- "ocd": "Organic Carbon Density",
101
- "phh2o": "Soil pH",
102
- "sand": "Sand Content",
103
- "silt": "Silt Content",
104
- "soc": "Soil Organic Carbon",
105
- "wv0010": "Volumetric Water Content (0-10cm)",
106
- "wv0033": "Volumetric Water Content (10-33cm)",
107
- "wv1500": "Volumetric Water Content (1500kPa)"
108
- }
109
-
110
  @app.route('/get_soil_properties', methods=['GET'])
111
  def get_soil_properties():
 
112
  lat = request.args.get('lat')
113
  lon = request.args.get('lon')
114
  lat, lon = validate_coordinates(lat, lon)
@@ -116,39 +100,45 @@ def get_soil_properties():
116
  return jsonify({"error": "Invalid coordinates"}), 400
117
 
118
  try:
119
- # Use the correct host; note that rest.isric.org is now used instead of rest.soilgrids.org
120
  prop_url = "https://rest.isric.org/soilgrids/v2.0/properties/query"
121
- # Provide the soil property codes as a comma-separated string
122
- properties = "bdod,cec,cfvo,clay,nitrogen,ocd,phh2o,sand,silt,soc,wv0010,wv0033,wv1500"
123
  prop_params = {
124
- "lat": lat,
125
- "lon": lon,
126
- "property": properties,
 
 
 
 
127
  "depth": "5-15cm",
128
  "value": "mean"
129
  }
130
  headers = {"accept": "application/json"}
131
- response = requests.get(prop_url, params=prop_params, headers=headers, timeout=10)
132
  response.raise_for_status()
133
  prop_data = response.json()
134
 
135
- # Uncomment the following line to print the entire API response for debugging:
136
- # print(json.dumps(prop_data, indent=2))
137
-
138
  table_data = []
139
- # Loop through each layer in the response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  for layer in prop_data.get('properties', {}).get('layers', []):
141
  parameter = layer.get('name')
142
  display_name = PARAMETER_NAMES.get(parameter, parameter)
143
- depths = layer.get('depths', [])
144
- if not depths:
145
- continue
146
- # Extract the mean value from the first depth entry
147
- value_dict = depths[0].get('values', {})
148
- value = value_dict.get('mean')
149
  if value is None:
150
  continue
151
- # Convert values for specific parameters
152
  if parameter in ["wv0010", "wv0033", "wv1500"]:
153
  final_value = value / 10.0
154
  unit = layer.get('unit_measure', {}).get("target_units", "")
@@ -159,11 +149,11 @@ def get_soil_properties():
159
  final_value = value
160
  unit = layer.get('unit_measure', {}).get("mapped_units", "")
161
  table_data.append([display_name, final_value, unit])
 
162
  return jsonify({"soil_properties": table_data})
163
  except Exception as e:
164
  return jsonify({"error": str(e)}), 500
165
 
166
-
167
  def call_gemini_api(input_data):
168
  language = input_data.get('language', 'English')
169
  prompt = f"""
@@ -208,8 +198,6 @@ Create a visually appealing, farmer-friendly pest outbreak report in Markdown wi
208
  13. Do not include long paragraphs; keep the language simple and the report well-formatted.
209
  14. Highlight important points (such as key damages, recommendations, pest names, key seasons) with yellow highlighters (only highlight key points, not the text).
210
  Please provide the complete report in {language} language only.
211
- also note that i want poepr format heaidng green stlying tables, and proper hihglighting all prpepr ,proper rendering of tbales in first attmept itself and tkaer care of it in evry sttrmept not dynamic everytime,should be uniform everytime
212
- okay and dont print any other useless contiant like imrovments done, disclaimer,stlying imroved eetc..
213
  """
214
  response = client.models.generate_content(
215
  model="gemini-2.0-flash",
@@ -217,6 +205,7 @@ okay and dont print any other useless contiant like imrovments done, disclaimer,
217
  )
218
  return response.text
219
 
 
220
  @app.route('/predict', methods=['POST'])
221
  def predict():
222
  form_data = request.form.to_dict()
@@ -347,4 +336,4 @@ def predict():
347
 
348
 
349
  if __name__ == '__main__':
350
- app.run(debug=True)
 
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:
17
+ return float(lat), float(lon)
18
+ except (TypeError, ValueError):
19
+ return None, None
20
+
21
 
22
  @app.route('/')
23
  def index():
24
  return render_template('index.html')
25
 
26
+
27
  @app.route('/get_weather_data', methods=['GET'])
28
  def get_weather_data():
29
  """
 
48
  "hourly": "relative_humidity_2m,soil_moisture_3_to_9cm,cloudcover,windspeed_10m",
49
  "timezone": "auto"
50
  }
51
+ resp = requests.get(forecast_url, params=forecast_params)
 
52
  resp.raise_for_status()
53
  data = resp.json()
54
 
 
90
  return jsonify({"error": str(e)}), 500
91
 
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  @app.route('/get_soil_properties', methods=['GET'])
94
  def get_soil_properties():
95
+ """Fetch soil properties using SoilGrids API and map to user-friendly names."""
96
  lat = request.args.get('lat')
97
  lon = request.args.get('lon')
98
  lat, lon = validate_coordinates(lat, lon)
 
100
  return jsonify({"error": "Invalid coordinates"}), 400
101
 
102
  try:
 
103
  prop_url = "https://rest.isric.org/soilgrids/v2.0/properties/query"
 
 
104
  prop_params = {
105
+ "lon": str(lon),
106
+ "lat": str(lat),
107
+ "property": [
108
+ "bdod", "cec", "cfvo", "clay", "nitrogen",
109
+ "ocd", "phh2o", "sand", "silt",
110
+ "soc", "wv0010", "wv0033", "wv1500"
111
+ ],
112
  "depth": "5-15cm",
113
  "value": "mean"
114
  }
115
  headers = {"accept": "application/json"}
116
+ response = requests.get(prop_url, params=prop_params, headers=headers)
117
  response.raise_for_status()
118
  prop_data = response.json()
119
 
 
 
 
120
  table_data = []
121
+ PARAMETER_NAMES = {
122
+ "bdod": "Bulk Density",
123
+ "cec": "CEC",
124
+ "cfvo": "Field Capacity",
125
+ "clay": "Clay",
126
+ "nitrogen": "Nitrogen",
127
+ "ocd": "Organic Carbon Density",
128
+ "phh2o": "pH",
129
+ "sand": "Sand",
130
+ "silt": "Silt",
131
+ "soc": "Soil Organic Carbon",
132
+ "wv0010": "Volumetric Water Content (0-10cm)",
133
+ "wv0033": "Volumetric Water Content (10-33cm)",
134
+ "wv1500": "Volumetric Water Content (1500)"
135
+ }
136
  for layer in prop_data.get('properties', {}).get('layers', []):
137
  parameter = layer.get('name')
138
  display_name = PARAMETER_NAMES.get(parameter, parameter)
139
+ value = layer.get('depths', [{}])[0].get('values', {}).get('mean')
 
 
 
 
 
140
  if value is None:
141
  continue
 
142
  if parameter in ["wv0010", "wv0033", "wv1500"]:
143
  final_value = value / 10.0
144
  unit = layer.get('unit_measure', {}).get("target_units", "")
 
149
  final_value = value
150
  unit = layer.get('unit_measure', {}).get("mapped_units", "")
151
  table_data.append([display_name, final_value, unit])
152
+
153
  return jsonify({"soil_properties": table_data})
154
  except Exception as e:
155
  return jsonify({"error": str(e)}), 500
156
 
 
157
  def call_gemini_api(input_data):
158
  language = input_data.get('language', 'English')
159
  prompt = f"""
 
198
  13. Do not include long paragraphs; keep the language simple and the report well-formatted.
199
  14. Highlight important points (such as key damages, recommendations, pest names, key seasons) with yellow highlighters (only highlight key points, not the text).
200
  Please provide the complete report in {language} language only.
 
 
201
  """
202
  response = client.models.generate_content(
203
  model="gemini-2.0-flash",
 
205
  )
206
  return response.text
207
 
208
+
209
  @app.route('/predict', methods=['POST'])
210
  def predict():
211
  form_data = request.form.to_dict()
 
336
 
337
 
338
  if __name__ == '__main__':
339
+ app.run(debug=True)