rajkhanke commited on
Commit
f2a0c2b
·
verified ·
1 Parent(s): 8c36229

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +307 -0
  2. templates/index.html +728 -0
  3. templates/index1.html +185 -0
app.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify, render_template
2
+ import json
3
+ import requests
4
+ import random
5
+ import math
6
+ import os
7
+ from dotenv import load_dotenv
8
+
9
+ load_dotenv() # Load environment variables from .env file
10
+
11
+ app = Flask(__name__)
12
+
13
+ GEMINI_API_KEY = "AIzaSyDkiYr-eSkqIXpZ1fHlik_YFsFtfQoFi0w"
14
+ NOMINATIM_USER_AGENT = "GeoSafeConstruct/1.0 ([email protected])" # IMPORTANT: Change to your app name and contact email
15
+
16
+
17
+ # --- Nominatim API Functions ---
18
+ def get_location_name_from_coords(lat, lon):
19
+ """Fetches a location name/address from coordinates using Nominatim."""
20
+ headers = {"User-Agent": NOMINATIM_USER_AGENT}
21
+ url = f"https://nominatim.openstreetmap.org/reverse?format=json&lat={lat}&lon={lon}&zoom=16&addressdetails=1"
22
+ try:
23
+ response = requests.get(url, headers=headers, timeout=10)
24
+ response.raise_for_status()
25
+ data = response.json()
26
+ # Construct a readable address, prioritizing certain fields
27
+ address = data.get('address', {})
28
+ parts = [
29
+ address.get('road'), address.get('neighbourhood'), address.get('suburb'),
30
+ address.get('city_district'), address.get('city'), address.get('town'),
31
+ address.get('village'), address.get('county'), address.get('state'),
32
+ address.get('postcode'), address.get('country')
33
+ ]
34
+ # Filter out None values and join
35
+ display_name = data.get('display_name', "Unknown Location")
36
+ filtered_parts = [part for part in parts if part]
37
+ if len(filtered_parts) > 3: # If many parts, use display_name for brevity
38
+ return display_name
39
+ elif filtered_parts:
40
+ return ", ".join(filtered_parts[:3]) # Take first few relevant parts
41
+ return display_name # Fallback to full display_name
42
+ except requests.exceptions.RequestException as e:
43
+ print(f"Nominatim reverse geocoding error: {e}")
44
+ return f"Area around {lat:.3f}, {lon:.3f}"
45
+ except (json.JSONDecodeError, KeyError) as e:
46
+ print(f"Nominatim response parsing error: {e}")
47
+ return f"Area around {lat:.3f}, {lon:.3f}"
48
+
49
+
50
+ def get_coords_from_location_name(query):
51
+ """Fetches coordinates from a location name/address using Nominatim."""
52
+ headers = {"User-Agent": NOMINATIM_USER_AGENT}
53
+ url = f"https://nominatim.openstreetmap.org/search?q={requests.utils.quote(query)}&format=json&limit=1"
54
+ try:
55
+ response = requests.get(url, headers=headers, timeout=10)
56
+ response.raise_for_status()
57
+ data = response.json()
58
+ if data and isinstance(data, list) and len(data) > 0:
59
+ return {
60
+ "latitude": float(data[0].get("lat")),
61
+ "longitude": float(data[0].get("lon")),
62
+ "display_name": data[0].get("display_name")
63
+ }
64
+ return None
65
+ except requests.exceptions.RequestException as e:
66
+ print(f"Nominatim geocoding error: {e}")
67
+ return None
68
+ except (json.JSONDecodeError, KeyError, IndexError) as e:
69
+ print(f"Nominatim geocoding response parsing error: {e}")
70
+ return None
71
+
72
+
73
+ # --- Gemini API Functions ---
74
+ def call_gemini_api(prompt_text):
75
+ """Generic function to call Gemini API."""
76
+ if not GEMINI_API_KEY:
77
+ print("GEMINI_API_KEY not found in environment variables.")
78
+ return None, "Gemini API key not configured."
79
+
80
+ url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent"
81
+ headers = {
82
+ "Content-Type": "application/json",
83
+ "x-goog-api-key": GEMINI_API_KEY
84
+ }
85
+ payload = {
86
+ "contents": [{"parts": [{"text": prompt_text}]}],
87
+ "generationConfig": {
88
+ "response_mime_type": "application/json",
89
+ "temperature": 0.6, # Adjust for creativity vs. factuality
90
+ "topP": 0.9,
91
+ "topK": 40
92
+ },
93
+ "safetySettings": [ # Add safety settings if needed
94
+ {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
95
+ {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
96
+ {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
97
+ {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"}
98
+ ]
99
+ }
100
+
101
+ try:
102
+ response = requests.post(url, json=payload, headers=headers, timeout=60) # Increased timeout
103
+ response.raise_for_status()
104
+ gemini_response_data = response.json()
105
+
106
+ if 'candidates' not in gemini_response_data or not gemini_response_data['candidates']:
107
+ print("Gemini API Error: No candidates in response.")
108
+ print("Full Gemini Response:", gemini_response_data)
109
+ if 'promptFeedback' in gemini_response_data and 'blockReason' in gemini_response_data['promptFeedback']:
110
+ return None, f"Content blocked by API: {gemini_response_data['promptFeedback']['blockReason']}"
111
+ return None, "Gemini API returned no content."
112
+
113
+ json_text_content = gemini_response_data['candidates'][0]['content']['parts'][0]['text']
114
+
115
+ # Attempt to clean JSON string if it's wrapped in markdown
116
+ if json_text_content.strip().startswith("```json"):
117
+ json_text_content = json_text_content.strip()[7:]
118
+ if json_text_content.strip().endswith("```"):
119
+ json_text_content = json_text_content.strip()[:-3]
120
+
121
+ return json.loads(json_text_content.strip()), None
122
+ except requests.exceptions.Timeout:
123
+ print("Gemini API call timed out.")
124
+ return None, "Analysis request timed out. Please try again."
125
+ except requests.exceptions.RequestException as e:
126
+ print(f"Error calling Gemini API (RequestException): {e}")
127
+ return None, f"Could not connect to analysis service: {e}"
128
+ except json.JSONDecodeError as e:
129
+ print(f"Error decoding JSON from Gemini API: {e}")
130
+ print(f"Received text for JSON parsing: {json_text_content if 'json_text_content' in locals() else 'N/A'}")
131
+ return None, "AI returned an invalid response format. Please try again."
132
+ except (KeyError, IndexError) as e:
133
+ print(f"Error parsing Gemini API response structure: {e}")
134
+ print(f"Gemini response: {gemini_response_data if 'gemini_response_data' in locals() else 'N/A'}")
135
+ return None, "AI returned an unexpected response structure."
136
+ except Exception as e:
137
+ print(f"An unexpected error occurred during Gemini call: {e}")
138
+ return None, f"An unexpected error occurred: {e}"
139
+
140
+
141
+ def get_safety_analysis_with_gemini(latitude, longitude, location_address):
142
+ """
143
+ Calls Gemini API to analyze construction safety.
144
+ """
145
+ prompt = f"""
146
+ **Objective:** Provide a detailed and realistic construction site safety analysis for the location: {location_address} (Latitude: {latitude}, Longitude: {longitude}).
147
+
148
+ **Output Format:** STRICTLY JSON. Do NOT include any text outside the JSON structure (e.g., no '```json' or '```' wrappers).
149
+
150
+ **JSON Structure:**
151
+ {{
152
+ "location_name": "{location_address}", // Use the provided address
153
+ "safety_score": "integer (0-100, overall safety score, be critical and realistic)",
154
+ "suitability_statement": "string (e.g., 'Generally Suitable with Mitigations', 'High Caution Advised', 'Not Recommended without Major Intervention')",
155
+ "summary_assessment": "string (3-4 sentences summarizing key findings, suitability, and major concerns. Be specific.)",
156
+ "geological_risks": {{
157
+ "earthquake_risk": {{
158
+ "level": "string ('Low', 'Medium', 'High', 'Very High', 'Not Assessed')",
159
+ "details": "string (Specifics like proximity to faults, historical activity, soil liquefaction potential if known. If not assessed, state why.)"
160
+ }},
161
+ "landslide_risk": {{
162
+ "level": "string ('Low', 'Medium', 'High', 'Very High', 'Not Assessed')",
163
+ "details": "string (Slope stability, soil type, vegetation, historical incidents. If not assessed, state why.)"
164
+ }},
165
+ "soil_stability": {{
166
+ "type": "string ('Stable', 'Moderately Stable', 'Unstable', 'Variable', 'Requires Investigation')",
167
+ "concerns": ["string array (e.g., 'Expansive clays present', 'High water table', 'Poor drainage', 'Subsidence risk')"]
168
+ }}
169
+ }},
170
+ "hydrological_risks": {{
171
+ "flood_risk": {{
172
+ "level": "string ('Low', 'Medium', 'High', 'Very High', 'Not Assessed')",
173
+ "details": "string (Proximity to water bodies, floodplain maps, historical flooding, drainage issues. If not assessed, state why.)"
174
+ }},
175
+ "tsunami_risk": {{ // Only include if geographically relevant (coastal)
176
+ "level": "string ('Negligible', 'Low', 'Medium', 'High')",
177
+ "details": "string (Distance from coast, elevation, historical data.)"
178
+ }}
179
+ }},
180
+ "other_environmental_risks": [ // Array of objects, include if relevant
181
+ {{ "type": "Wildfire", "level": "string ('Low', 'Medium', 'High')", "details": "string (Vegetation, climate, fire history)" }},
182
+ {{ "type": "Extreme Weather (Hurricanes/Tornadoes/High Winds)", "level": "string ('Low', 'Medium', 'High')", "details": "string (Regional patterns, building code requirements)" }},
183
+ {{ "type": "Industrial Hazards", "level": "string ('Low', 'Medium', 'High')", "details": "string (Proximity to industrial plants, pipelines, hazardous material routes)" }}
184
+ ],
185
+ "key_risk_factors_summary": ["string array (Bulleted list of 3-5 most critical risk factors for this specific site)"],
186
+ "mitigation_recommendations": ["string array (Actionable, specific recommendations, e.g., 'Conduct Level 2 Geotechnical Survey focusing on shear strength', 'Implement earthquake-resistant design to Zone IV standards', 'Elevate foundation by 1.5m above base flood elevation')"],
187
+ "further_investigations_needed": ["string array (e.g., 'Detailed hydrological study', 'Environmental Impact Assessment', 'Traffic impact study')"],
188
+ "alternative_locations_analysis": [ // Up to 2-3 alternatives. If none are significantly better, state that.
189
+ {{
190
+ "name_suggestion": "string (Suggest a conceptual name like 'North Ridge Site' or 'Valley View Plot')",
191
+ "latitude": "float (as string, e.g., '18.5234')",
192
+ "longitude": "float (as string, e.g., '73.8567')",
193
+ "estimated_distance_km": "float (as string, e.g., '8.5')",
194
+ "brief_justification": "string (Why is this a potential alternative? E.g., 'Appears to be on more stable ground', 'Further from flood plain')",
195
+ "potential_pros": ["string array"],
196
+ "potential_cons": ["string array"],
197
+ "comparative_safety_score_estimate": "integer (0-100, relative to primary site)"
198
+ }}
199
+ ],
200
+ "data_confidence_level": "string ('Low', 'Medium', 'High' - based on assumed availability of public data for this general region, not specific site data which is unknown to you)",
201
+ "disclaimer": "This AI-generated analysis is for preliminary informational purposes only and not a substitute for professional engineering, geological, and environmental assessments. On-site investigations are crucial."
202
+ }}
203
+
204
+ **Guidelines for Content:**
205
+ - make sumre rnaodmness in score generation not same view ppijn t everytime
206
+ - Be realistic. If data for a specific risk is unlikely to be publicly available for a random coordinate, mark it 'Not Assessed' and explain.
207
+ - Focus on actionable insights.
208
+ - For alternative locations, provide *different* lat/lon coordinates that are plausibly nearby (within 5-20km).
209
+ - Ensure all string values are properly quoted. Ensure latitudes and longitudes for alternatives are strings representing floats.
210
+ - The safety_score should reflect a comprehensive evaluation of all risks.
211
+ - proper spacing and upo down margins shoudl be there
212
+ """
213
+ return call_gemini_api(prompt)
214
+
215
+
216
+ # --- Flask Routes ---
217
+ @app.route('/')
218
+ def index():
219
+ return render_template('index.html')
220
+
221
+
222
+ @app.route('/api/geocode', methods=['POST'])
223
+ def geocode_location():
224
+ data = request.json
225
+ query = data.get('query')
226
+ if not query:
227
+ return jsonify({"error": "Query parameter is required."}), 400
228
+
229
+ coords_data = get_coords_from_location_name(query)
230
+ if coords_data:
231
+ return jsonify(coords_data), 200
232
+ else:
233
+ return jsonify({"error": "Location not found or geocoding failed."}), 404
234
+
235
+
236
+ @app.route('/api/analyze_location', methods=['POST'])
237
+ def analyze_location_route():
238
+ data = request.json
239
+ try:
240
+ latitude = float(data.get('latitude'))
241
+ longitude = float(data.get('longitude'))
242
+ except (TypeError, ValueError):
243
+ return jsonify({"error": "Invalid latitude or longitude provided."}), 400
244
+
245
+ # Get a human-readable name for the primary location
246
+ primary_location_address = get_location_name_from_coords(latitude, longitude)
247
+
248
+ # Call Gemini for the main analysis
249
+ analysis_data, error = get_safety_analysis_with_gemini(latitude, longitude, primary_location_address)
250
+
251
+ if error:
252
+ # Fallback to a simpler mock-like structure if Gemini fails critically
253
+ return jsonify({
254
+ "error_message": error,
255
+ "location_name": primary_location_address,
256
+ "safety_score": random.randint(20, 50), # Low score to indicate issue
257
+ "summary_assessment": f"Could not perform detailed analysis due to: {error}. Basic location: {primary_location_address}.",
258
+ "suitability_statement": "Analysis Incomplete",
259
+ "geological_risks": {"earthquake_risk": {"level": "Not Assessed", "details": error}},
260
+ "hydrological_risks": {"flood_risk": {"level": "Not Assessed", "details": error}},
261
+ "disclaimer": "A technical issue prevented full analysis."
262
+ }), 500
263
+
264
+ # Post-process alternative locations to get their names
265
+ if analysis_data.get("alternative_locations_analysis"):
266
+ for alt_loc in analysis_data["alternative_locations_analysis"]:
267
+ try:
268
+ alt_lat = float(alt_loc.get("latitude"))
269
+ alt_lon = float(alt_loc.get("longitude"))
270
+ alt_loc["actual_name"] = get_location_name_from_coords(alt_lat, alt_lon)
271
+ # Ensure distance is calculated if not provided by Gemini or if it's nonsensical
272
+ if not alt_loc.get("estimated_distance_km") or float(alt_loc.get("estimated_distance_km", 0)) == 0:
273
+ alt_loc["estimated_distance_km"] = str(
274
+ calculate_haversine_distance(latitude, longitude, alt_lat, alt_lon))
275
+
276
+ except (TypeError, ValueError, KeyError) as e:
277
+ print(f"Error processing alternative location coords: {e}, data: {alt_loc}")
278
+ alt_loc["actual_name"] = "Nearby Area (details unavailable)"
279
+ # Fallback if lat/lon are missing or invalid for an alternative
280
+ if "latitude" not in alt_loc or "longitude" not in alt_loc:
281
+ alt_loc["latitude"] = str(latitude + (random.random() - 0.5) * 0.05) # Small offset
282
+ alt_loc["longitude"] = str(longitude + (random.random() - 0.5) * 0.05)
283
+
284
+ return jsonify(analysis_data), 200
285
+
286
+
287
+ def calculate_haversine_distance(lat1, lon1, lat2, lon2):
288
+ R = 6371 # Radius of Earth in kilometers
289
+ try:
290
+ lat1_rad, lon1_rad = math.radians(float(lat1)), math.radians(float(lon1))
291
+ lat2_rad, lon2_rad = math.radians(float(lat2)), math.radians(float(lon2))
292
+ except (ValueError, TypeError):
293
+ print(f"Error converting lat/lon to float for Haversine: {lat1}, {lon1}, {lat2}, {lon2}")
294
+ return 0.0 # Fallback
295
+ dlon = lon2_rad - lon1_rad
296
+ dlat = lat2_rad - lat1_rad
297
+ a = math.sin(dlat / 2) ** 2 + math.cos(lat1_rad) * math.cos(lat2_rad) * math.sin(dlon / 2) ** 2
298
+ c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
299
+ distance = R * c
300
+ return round(distance, 1)
301
+
302
+
303
+ if __name__ == '__main__':
304
+ if not GEMINI_API_KEY:
305
+ print("CRITICAL ERROR: GEMINI_API_KEY is not set in the environment.")
306
+ print("Please create a .env file with GEMINI_API_KEY=YOUR_API_KEY or set it as an environment variable.")
307
+ app.run(debug=True, port=5000)
templates/index.html ADDED
@@ -0,0 +1,728 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>GeoSafe Construct | Professional AI Safety Analyzer</title>
7
+ <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet">
8
+ <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
9
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
10
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.5.5/css/simple-line-icons.css">
11
+
12
+ <style>
13
+ :root {
14
+ --primary-blue: #0072ff;
15
+ --primary-blue-dark: #005fcc;
16
+ --secondary-blue: #00c6ff;
17
+ --text-dark: #1f2937;
18
+ --text-medium: #4b5563;
19
+ --text-light: #6b7280;
20
+ --card-bg: #ffffff;
21
+ --body-bg: #f8f9fa;
22
+ --border-color: #dee2e6;
23
+ --success-bg: #e6f7f0; --success-text: #0a6847; --success-border: #b3e0c8; /* Softer Greens */
24
+ --warning-bg: #fff8e1; --warning-text: #795502; --warning-border: #ffecb3; /* Softer Yellows */
25
+ --danger-bg: #fdecea; --danger-text: #8c1c13; --danger-border: #f9c1ba; /* Softer Reds */
26
+ --info-bg: #e0f7fa; --info-text: #006064; --info-border: #b2ebf2; /* Softer Cyans/Blues */
27
+ --neutral-bg: #f1f3f5; --neutral-text: #495057; --neutral-border: #ced4da; /* Softer Grays */
28
+ }
29
+
30
+ body { font-family: 'Inter', sans-serif; background-color: var(--body-bg); color: var(--text-dark); -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }
31
+ .app-header { background: linear-gradient(135deg, var(--secondary-blue) 0%, var(--primary-blue) 100%); color: white; padding: 2rem 0; margin-bottom: 2.5rem; box-shadow: 0 4px 12px rgba(0,114,255,0.2); }
32
+ .app-header h1 { text-shadow: 0 1px 2px rgba(0,0,0,0.15); font-weight: 800; }
33
+ .app-header p { opacity: 0.9; }
34
+
35
+ .map-container { border-radius: 0.625rem; border: 1px solid var(--border-color); box-shadow: 0 1px 3px rgba(0,0,0,0.05); overflow: hidden; /* Important for border radius on map */ }
36
+ #input-map { height: 280px; cursor: crosshair; }
37
+ #results-map { height: 400px; }
38
+
39
+ .leaflet-popup-content-wrapper { border-radius: 0.5rem; background: var(--card-bg); box-shadow: 0 4px 15px rgba(0,0,0,0.1); border: 1px solid var(--border-color); }
40
+ .leaflet-popup-content { margin: 15px !important; font-size: 0.875rem; color: var(--text-dark); }
41
+
42
+ .risk-badge { padding: 0.3rem 0.8rem; border-radius: 9999px; font-size: 0.65rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.75px; display: inline-block; border: 1px solid; line-height: 1; }
43
+ .risk-low, .risk-negligible, .risk-stable { background-color: var(--success-bg); color: var(--success-text); border-color: var(--success-border); }
44
+ .risk-medium, .risk-moderately_stable { background-color: var(--warning-bg); color: var(--warning-text); border-color: var(--warning-border); }
45
+ .risk-high, .risk-very_high, .risk-unstable { background-color: var(--danger-bg); color: var(--danger-text); border-color: var(--danger-border); }
46
+ .risk-not_assessed, .risk-requires_investigation, .risk-variable { background-color: var(--neutral-bg); color: var(--neutral-text); border-color: var(--neutral-border); }
47
+
48
+ .score-gauge-container { text-align: center; margin-bottom: 1.5rem; }
49
+ .score-gauge { position: relative; width: 200px; height: 100px; overflow: hidden; margin: 0 auto 0.75rem auto; }
50
+ .score-gauge-bg { width: 200px; height: 200px; border-radius: 50%; background: conic-gradient(from 180deg, #EF4444 0%, #EF4444 16.67%, #F59E0B 16.67%, #F59E0B 33.33%, #10B981 33.33%, #10B981 50%, var(--body-bg) 50.01%, var(--body-bg) 100%); position: absolute; top: 0; left: 0; }
51
+ .score-gauge-meter { width: 200px; height: 200px; border-radius: 50%; background: var(--card-bg); position: absolute; top: 0; left: 0; transform-origin: center center; transition: transform 1s cubic-bezier(0.68, -0.55, 0.27, 1.55); clip-path: polygon(0% 0%, 100% 0%, 100% 50%, 0% 50%); transform: rotate(0deg); }
52
+ .score-gauge-overlay { width: 160px; height: 80px; background: var(--card-bg); border-radius: 160px 160px 0 0 / 80px 80px 0 0; position: absolute; bottom: 0; left: 20px; }
53
+ .safety-score-value-display { font-size: 3.25rem; font-weight: 800; line-height: 1; margin-top: 0.25rem; transition: color 0.5s; }
54
+ .safety-score-label-display { font-size: 0.8rem; color: var(--text-medium); text-transform: uppercase; letter-spacing: 1px; font-weight: 500; }
55
+
56
+ .card { background-color: var(--card-bg); border-radius: 0.875rem; box-shadow: 0 5px 15px rgba(0,0,0,0.06); padding: 2rem; margin-bottom: 2.5rem; border: 1px solid var(--border-color); transition: all 0.3s ease-in-out; }
57
+ .card:hover { box-shadow: 0 8px 25px rgba(0,0,0,0.08); transform: translateY(-3px); }
58
+ .card h2 { font-size: 1.5rem; font-weight: 700; } .card h3 { font-size: 1.2rem; font-weight: 600; }
59
+ .card p, .card li, .card span { color: var(--text-medium); line-height: 1.65; }
60
+ .card strong { color: var(--text-dark); font-weight: 600; } .card .text-xs { color: var(--text-light); }
61
+
62
+ .btn { padding: 0.875rem 1.75rem; font-weight: 600; border-radius: 0.5rem; transition: all 0.25s ease-in-out; display: inline-flex; align-items: center; justify-content: center; border: 1px solid transparent; cursor: pointer; text-transform: uppercase; letter-spacing: 0.5px; font-size: 0.875rem; }
63
+ .btn-primary { background-color: var(--primary-blue); color: white; box-shadow: 0 2px 5px rgba(0,114,255,0.2); }
64
+ .btn-primary:hover { background-color: var(--primary-blue-dark); transform: translateY(-2px); box-shadow: 0 4px 10px rgba(0,114,255,0.3); }
65
+ .btn-primary:disabled { background-color: #a0cfff; box-shadow: none; transform: none; cursor: not-allowed; }
66
+ .btn-secondary { background-color: var(--card-bg); border-color: var(--border-color); color: var(--primary-blue); }
67
+ .btn-secondary:hover { background-color: #f0f6ff; border-color: var(--primary-blue); color: var(--primary-blue-dark); transform: translateY(-2px); box-shadow: 0 4px 10px rgba(0,0,0,0.05); }
68
+
69
+ .icon-style { width: 1.125rem; height: 1.125rem; margin-right: 0.75rem; vertical-align: middle; }
70
+ .btn-spinner { width: 1.25em; height: 1.25em; border: 3px solid currentColor; border-right-color: transparent; border-radius: 50%; animation: spin 0.65s linear infinite; margin-left: 0.75em; }
71
+ @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
72
+
73
+ #analysis-overlay {
74
+ position: fixed; inset: 0;
75
+ background-color: rgba(0,0,0,0.35); /* Darker overlay */
76
+ backdrop-filter: blur(8px); /* Stronger blur */
77
+ display: flex; align-items: center; justify-content: center;
78
+ z-index: 10000; /* Higher z-index */
79
+ transition: opacity 0.3s ease-in-out, visibility 0.3s ease-in-out;
80
+ visibility: hidden; opacity: 0;
81
+ }
82
+ #analysis-overlay.visible { visibility: visible; opacity: 1; }
83
+
84
+ input[type="number"], input[type="text"] { border: 1px solid var(--border-color); border-radius: 0.5rem; padding: 0.875rem 1.125rem; color: var(--text-dark); width: 100%; background-color: #fff; transition: border-color 0.2s, box-shadow 0.2s; font-size: 0.9375rem; }
85
+ input[type="number"]:focus, input[type="text"]:focus { border-color: var(--primary-blue); box-shadow: 0 0 0 3px rgba(0, 114, 255, 0.2); outline: none; }
86
+ label { color: var(--text-medium); font-weight: 500; margin-bottom: 0.5rem; display: block; font-size: 0.875rem; }
87
+ .input-group { position: relative; }
88
+ .input-group .btn { position: absolute; right: 0.375rem; top: 50%; transform: translateY(-50%); padding: 0.625rem 1rem; font-size: 0.8rem; }
89
+
90
+ .accordion-item { border-bottom: 1px solid var(--border-color); }
91
+ .accordion-item:last-child { border-bottom: none; }
92
+ .accordion-header { display: flex; justify-content: space-between; align-items: center; padding: 1.25rem 0.75rem; cursor: pointer; transition: background-color 0.25s, color 0.25s; border-radius: 0.375rem; margin: 0.25rem 0; }
93
+ .accordion-header:hover { background-color: #eef2ff; /* Light indigo for hover */ color: var(--primary-blue-dark); }
94
+ .accordion-header.open { background-color: #e0e7ff; /* Slightly darker for open */ color: var(--primary-blue-dark); }
95
+ .accordion-header h3 { margin-bottom: 0; transition: color 0.25s; }
96
+ .accordion-content { max-height: 0; overflow: hidden; transition: max-height 0.5s cubic-bezier(0.4, 0, 0.2, 1), padding 0.5s cubic-bezier(0.4, 0, 0.2, 1); padding: 0 0.75rem; }
97
+ /* .accordion-content.open is handled by JS by setting max-height to scrollHeight */
98
+ .accordion-arrow { transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1); font-size: 1.2rem; color: var(--primary-blue); }
99
+ .accordion-header.open .accordion-arrow { transform: rotate(90deg); }
100
+
101
+ .custom-list li { padding-left: 1.75em; position: relative; margin-bottom: 0.625em; }
102
+ .custom-list li::before { font-family: 'simple-line-icons'; position: absolute; left: 0; top: 2px; font-size: 1em; transition: color 0.2s; }
103
+ #mitigation-recommendations-list li::before { content: "\e080"; color: var(--success-text); } /* Check */
104
+ #key-risk-factors-summary li::before { content: "\e090"; color: var(--danger-text); } /* Exclamation */
105
+ #further-investigations-list li::before { content: "\e003"; color: var(--warning-text); } /* Magnifying glass */
106
+
107
+ /* Styling for risk detail items inside accordion */
108
+ .risk-detail-item { padding: 0.75rem 0; border-bottom: 1px dashed #e5e7eb; }
109
+ .risk-detail-item:last-child { border-bottom: none; }
110
+ .risk-detail-item strong { display: block; margin-bottom: 0.25rem; }
111
+ .risk-detail-item .text-xs { margin-top: 0.25rem; }
112
+
113
+ </style>
114
+ </head>
115
+ <body class="antialiased">
116
+
117
+ <header class="app-header">
118
+ <div class="container mx-auto px-4 text-center">
119
+ <div class="inline-flex items-center p-2 rounded-lg">
120
+ <i class="icon-shield text-4xl mr-3"></i>
121
+ <h1 class="text-4xl sm:text-5xl tracking-tight">GeoSafe Construct</h1>
122
+ </div>
123
+ <p class="mt-2 text-lg">Professional AI-Powered Construction Site Safety Analysis</p>
124
+ </div>
125
+ </header>
126
+
127
+ <div class="container mx-auto px-4 w-full max-w-3xl pb-16">
128
+
129
+ <section id="input-section" class="card !pt-8">
130
+ <h2 class="text-2xl font-bold mb-8 text-center text-gray-700">Define Site for Analysis</h2>
131
+
132
+ <div class="mb-6">
133
+ <label for="location-query">Search Location (e.g., "Eiffel Tower, Paris" or Address):</label>
134
+ <div class="input-group">
135
+ <input type="text" id="location-query" placeholder="Enter address or place name...">
136
+ <button id="search-location-button" class="btn btn-secondary !py-3">
137
+ <i class="icon-magnifier mr-1"></i> Search
138
+ </button>
139
+ </div>
140
+ </div>
141
+ <p class="text-center text-sm text-gray-500 my-4">OR ENTER COORDINATES / CLICK MAP</p>
142
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-5 mb-5">
143
+ <div>
144
+ <label for="latitude">Latitude:</label>
145
+ <input type="number" id="latitude" name="latitude" step="any" value="18.520962" placeholder="e.g., 18.520962">
146
+ </div>
147
+ <div>
148
+ <label for="longitude">Longitude:</label>
149
+ <input type="number" id="longitude" name="longitude" step="any" value="73.857672" placeholder="e.g., 73.857672">
150
+ </div>
151
+ </div>
152
+
153
+ <div class="mb-6">
154
+ <label>Select precise location by clicking on the map:</label>
155
+ <div class="map-container">
156
+ <div id="input-map"></div>
157
+ </div>
158
+ </div>
159
+
160
+ <div class="flex flex-col sm:flex-row justify-center items-center gap-4 mt-8">
161
+ <button id="analyze-button" class="btn btn-primary w-full sm:w-auto">
162
+ <span id="button-text">Analyze Location</span>
163
+ <i id="analyze-icon" class="icon-paper-plane ml-2"></i>
164
+ <div id="button-spinner" class="btn-spinner hidden"></div>
165
+ </button>
166
+ <button id="use-my-location" class="btn btn-secondary w-full sm:w-auto">
167
+ <i class="icon-location-pin mr-2"></i>
168
+ Use My Current Location
169
+ </button>
170
+ </div>
171
+ </section>
172
+
173
+ <div id="analysis-overlay" class="fixed inset-0 flex items-center justify-start px-10">
174
+ <div class="bg-white p-10 rounded-xl shadow-2xl text-left">
175
+ <div class="w-16 h-16 border-6 border-blue-500 border-t-transparent rounded-full animate-spin mb-6"></div>
176
+ <p class="text-2xl font-semibold text-gray-700">Analyzing Location Data...</p>
177
+ <p class="text-lg text-gray-500 mt-2">This may take a few moments.</p>
178
+ </div>
179
+ </div>
180
+
181
+
182
+ <div id="error-message-container" class="hidden my-6 p-5 border-l-4 rounded-md shadow-md"> {/* Base classes, specific colors in JS */}
183
+ <div class="flex">
184
+ <div class="flex-shrink-0">
185
+ <i class="icon-info text-2xl"></i> {/* Icon class will be set by JS */}
186
+ </div>
187
+ <div class="ml-4">
188
+ <h3 class="text-lg font-bold">Notice</h3> {/* Title will be set by JS */}
189
+ <div class="mt-2 text-md">
190
+ <p id="error-text"></p>
191
+ </div>
192
+ </div>
193
+ </div>
194
+ </div>
195
+
196
+ <section id="results-section" class="hidden">
197
+
198
+ <div class="card">
199
+ <div class="flex flex-col sm:flex-row justify-between items-start mb-4">
200
+ <div>
201
+ <h2 class="text-2xl font-bold" id="location-name-display">Site Assessment</h2>
202
+ <p class="text-md text-gray-500" id="current-coords-display">Lat: N/A, Lon: N/A</p>
203
+ </div>
204
+ <span id="suitability-badge" class="mt-2 sm:mt-0 px-4 py-2 text-md font-semibold rounded-full self-start sm:self-center">N/A</span>
205
+ </div>
206
+
207
+ <div class="score-gauge-container mt-4 mb-5">
208
+ <div class="score-gauge">
209
+ <div class="score-gauge-bg"></div>
210
+ <div id="score-gauge-meter-dynamic" class="score-gauge-meter"></div>
211
+ <div class="score-gauge-overlay"></div>
212
+ </div>
213
+ <div id="safety-score-value-display" class="safety-score-value-display">N/A</div>
214
+ <div class="safety-score-label-display">Overall Safety Score</div>
215
+ </div>
216
+
217
+ <div class="mt-6">
218
+ <h3 class="text-xl font-semibold mb-2">Assessment Summary:</h3>
219
+ <p id="summary-assessment" class="text-md leading-relaxed">Loading assessment...</p>
220
+ </div>
221
+ <div class="mt-4">
222
+ <h3 class="text-xl font-semibold mb-1">Suitability:</h3>
223
+ <p id="suitability-statement" class="text-md font-bold">N/A</p>
224
+ </div>
225
+ </div>
226
+
227
+ <div class="card">
228
+ <h2 class="text-2xl font-bold mb-6">Detailed Risk Analysis</h2>
229
+
230
+ <div class="accordion-item">
231
+ <div class="accordion-header">
232
+ <h3 class="text-xl flex items-center text-red-700"><i class="icon-layers mr-3"></i>Geological Risks</h3>
233
+ <i class="icon-arrow-right accordion-arrow"></i>
234
+ </div>
235
+ <div class="accordion-content">
236
+ <div class="space-y-5 p-3"> {/* Increased padding and spacing */}
237
+ <div id="earthquake-risk-details" class="risk-detail-item"></div>
238
+ <div id="landslide-risk-details" class="risk-detail-item"></div>
239
+ <div id="soil-stability-details" class="risk-detail-item"></div>
240
+ </div>
241
+ </div>
242
+ </div>
243
+
244
+ <div class="accordion-item">
245
+ <div class="accordion-header">
246
+ <h3 class="text-xl flex items-center text-blue-700"><i class="icon-drop mr-3"></i>Hydrological Risks</h3>
247
+ <i class="icon-arrow-right accordion-arrow"></i>
248
+ </div>
249
+ <div class="accordion-content">
250
+ <div class="space-y-5 p-3">
251
+ <div id="flood-risk-details" class="risk-detail-item"></div>
252
+ <div id="tsunami-risk-details" class="hidden risk-detail-item"></div>
253
+ </div>
254
+ </div>
255
+ </div>
256
+
257
+ <div id="other-environmental-risks-accordion" class="accordion-item hidden">
258
+ <div class="accordion-header">
259
+ <h3 class="text-xl flex items-center text-purple-700"><i class="icon-globe-alt mr-3"></i>Other Environmental Risks</h3>
260
+ <i class="icon-arrow-right accordion-arrow"></i>
261
+ </div>
262
+ <div class="accordion-content">
263
+ <div id="other-environmental-risks-list" class="space-y-5 p-3"></div>
264
+ </div>
265
+ </div>
266
+ <hr class="my-8 border-gray-200">
267
+ <div>
268
+ <h3 class="text-xl font-semibold mb-3 flex items-center"><i class="icon-flag mr-3 text-red-600"></i>Key Risk Factors:</h3>
269
+ <ul id="key-risk-factors-summary" class="custom-list space-y-2 text-md"></ul>
270
+ </div>
271
+ </div>
272
+
273
+ <div class="card">
274
+ <h2 class="text-2xl font-bold mb-6">Recommendations & Further Actions</h2>
275
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-x-10 gap-y-8">
276
+ <div>
277
+ <h3 class="text-xl font-semibold mb-4 flex items-center text-green-700">
278
+ <i class="icon-check mr-3"></i>Mitigation Recommendations
279
+ </h3>
280
+ <ul id="mitigation-recommendations-list" class="custom-list space-y-2 text-md"></ul>
281
+ </div>
282
+ <div>
283
+ <h3 class="text-xl font-semibold mb-4 flex items-center text-yellow-700">
284
+ <i class="icon-magnifier-add mr-3"></i>Further Investigations Needed
285
+ </h3>
286
+ <ul id="further-investigations-list" class="custom-list space-y-2 text-md"></ul>
287
+ </div>
288
+ </div>
289
+ </div>
290
+
291
+ <div class="card">
292
+ <h2 class="text-2xl font-bold mb-5">Site Map & Alternatives Overview</h2>
293
+ <div class="map-container">
294
+ <div id="results-map"></div>
295
+ </div>
296
+ </div>
297
+
298
+ <div id="alternative-locations-section" class="card hidden">
299
+ <h2 class="text-2xl font-bold mb-5 flex items-center">
300
+ <i class="icon-directions mr-3 text-blue-600"></i>Alternative Location Analysis
301
+ </h2>
302
+ <div id="alternative-locations-container" class="space-y-6">
303
+ <p class="text-md text-gray-500">No significantly better alternatives identified or loading...</p>
304
+ </div>
305
+ </div>
306
+
307
+ <div class="card text-md">
308
+ <p><strong>Data Confidence:</strong> <span id="data-confidence" class="font-semibold">N/A</span></p>
309
+ <p id="disclaimer-text" class="mt-3 text-sm text-gray-500 italic">Disclaimer will be loaded here.</p>
310
+ </div>
311
+ </section>
312
+ </div>
313
+
314
+ <script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
315
+
316
+ <script>
317
+ // --- Leaflet Icons ---
318
+ const createIcon = (color) => L.icon({
319
+ iconUrl: `https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-${color}.png`,
320
+ shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
321
+ iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34], shadowSize: [41, 41]
322
+ });
323
+ const primaryLocationIcon = createIcon('blue');
324
+ const saferAlternativeIcon = createIcon('green');
325
+ const otherAlternativeIcon = createIcon('orange');
326
+ const selectionIcon = createIcon('red');
327
+
328
+ // --- DOM Element References (ensure all are captured) ---
329
+ let inputMap, resultsMap, inputMarker, currentResultMarker;
330
+ const alternativeMarkers = [];
331
+
332
+ const latitudeInput = document.getElementById('latitude');
333
+ const longitudeInput = document.getElementById('longitude');
334
+ const locationQueryInput = document.getElementById('location-query');
335
+ const searchLocationButton = document.getElementById('search-location-button');
336
+ const analyzeButton = document.getElementById('analyze-button');
337
+ const buttonText = document.getElementById('button-text');
338
+ const buttonSpinner = document.getElementById('button-spinner');
339
+ const analyzeIcon = document.getElementById('analyze-icon');
340
+ const useMyLocationButton = document.getElementById('use-my-location');
341
+
342
+ const resultsSection = document.getElementById('results-section');
343
+ const analysisOverlay = document.getElementById('analysis-overlay');
344
+ const errorMessageContainer = document.getElementById('error-message-container');
345
+ const errorText = document.getElementById('error-text');
346
+
347
+ const locationNameDisplay = document.getElementById('location-name-display');
348
+ const currentCoordsDisplay = document.getElementById('current-coords-display');
349
+ const suitabilityBadge = document.getElementById('suitability-badge');
350
+ const scoreValueDisplay = document.getElementById('safety-score-value-display');
351
+ const summaryAssessmentP = document.getElementById('summary-assessment');
352
+ const suitabilityStatementP = document.getElementById('suitability-statement');
353
+
354
+ const earthquakeRiskDetailsDiv = document.getElementById('earthquake-risk-details');
355
+ const landslideRiskDetailsDiv = document.getElementById('landslide-risk-details');
356
+ const soilStabilityDetailsDiv = document.getElementById('soil-stability-details');
357
+ const floodRiskDetailsDiv = document.getElementById('flood-risk-details');
358
+ const tsunamiRiskDetailsDiv = document.getElementById('tsunami-risk-details');
359
+ const otherEnvRisksAccordion = document.getElementById('other-environmental-risks-accordion');
360
+ const otherEnvRisksList = document.getElementById('other-environmental-risks-list');
361
+ const keyRiskFactorsUl = document.getElementById('key-risk-factors-summary');
362
+ const mitigationRecommendationsUl = document.getElementById('mitigation-recommendations-list');
363
+ const furtherInvestigationsUl = document.getElementById('further-investigations-list');
364
+ const altLocationsSection = document.getElementById('alternative-locations-section');
365
+ const altLocationsContainer = document.getElementById('alternative-locations-container');
366
+ const dataConfidenceSpan = document.getElementById('data-confidence');
367
+ const disclaimerP = document.getElementById('disclaimer-text');
368
+
369
+ // --- Initialization ---
370
+ document.addEventListener('DOMContentLoaded', () => {
371
+ analysisOverlay.classList.remove('visible');
372
+
373
+ inputMap = L.map('input-map', { scrollWheelZoom: true, attributionControl: false }).setView([18.520962, 73.857672], 12); // Default to Pune
374
+ L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18, opacity: 0.9 }).addTo(inputMap);
375
+ L.control.attribution({prefix: false}).addTo(inputMap);
376
+ updateInputMarker(18.520962, 73.857672);
377
+
378
+ inputMap.on('click', function(e) {
379
+ const lat = e.latlng.lat;
380
+ const lon = e.latlng.lng;
381
+ latitudeInput.value = lat.toFixed(6);
382
+ longitudeInput.value = lon.toFixed(6);
383
+ updateInputMarker(lat, lon);
384
+ locationQueryInput.value = '';
385
+ });
386
+
387
+ resultsMap = L.map('results-map', { scrollWheelZoom: false, attributionControl: false }).setView([20.5937, 78.9629], 5); // Default to India view
388
+ L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18, opacity: 0.9 }).addTo(resultsMap);
389
+ L.control.attribution({prefix: false}).addTo(resultsMap);
390
+
391
+ searchLocationButton.addEventListener('click', handleLocationSearch);
392
+ locationQueryInput.addEventListener('keypress', e => { if (e.key === 'Enter') handleLocationSearch(); });
393
+ analyzeButton.addEventListener('click', handleAnalysis);
394
+ useMyLocationButton.addEventListener('click', getUserLocationAndAnalyze);
395
+
396
+ document.querySelectorAll('.accordion-header').forEach(header => {
397
+ header.addEventListener('click', () => {
398
+ const content = header.nextElementSibling;
399
+ header.classList.toggle('open');
400
+ // content.classList.toggle('open'); // Replaced with direct style manipulation
401
+ if (content.style.maxHeight && content.style.maxHeight !== "0px") {
402
+ content.style.maxHeight = "0px";
403
+ content.style.paddingTop = "0px";
404
+ content.style.paddingBottom = "0px";
405
+ } else {
406
+ content.style.maxHeight = content.scrollHeight + "px";
407
+ content.style.paddingTop = "1rem"; // Or your desired padding
408
+ content.style.paddingBottom = "1rem";
409
+ }
410
+ });
411
+ });
412
+ });
413
+
414
+ // --- Core Functions ---
415
+ function updateInputMarker(lat, lon, zoomLevel = 13) {
416
+ if (inputMarker) inputMap.removeLayer(inputMarker);
417
+ inputMarker = L.marker([lat, lon], {icon: selectionIcon}).addTo(inputMap);
418
+ inputMap.setView([lat, lon], zoomLevel, {animate: true});
419
+ }
420
+
421
+ async function handleLocationSearch() {
422
+ const query = locationQueryInput.value.trim();
423
+ if (!query) { displayError("Please enter a location to search."); return; }
424
+
425
+ searchLocationButton.disabled = true;
426
+ const originalSearchHTML = searchLocationButton.innerHTML;
427
+ searchLocationButton.innerHTML = `<div class="btn-spinner !ml-0 !mr-0 !w-4 !h-4"></div>`;
428
+
429
+ try {
430
+ const response = await fetch('/api/geocode', {
431
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query })
432
+ });
433
+ const data = await response.json();
434
+ if (!response.ok || data.error) throw new Error(data.error || "Location not found.");
435
+
436
+ latitudeInput.value = parseFloat(data.latitude).toFixed(6);
437
+ longitudeInput.value = parseFloat(data.longitude).toFixed(6);
438
+ updateInputMarker(data.latitude, data.longitude, 15);
439
+ locationQueryInput.value = data.display_name;
440
+ hideError();
441
+ } catch (error) {
442
+ console.error("Geocoding error:", error);
443
+ displayError(error.message);
444
+ } finally {
445
+ searchLocationButton.disabled = false;
446
+ searchLocationButton.innerHTML = originalSearchHTML;
447
+ }
448
+ }
449
+
450
+ function showLoadingState(isLoading) {
451
+ if (isLoading) {
452
+ analysisOverlay.classList.add('visible');
453
+ buttonText.textContent = 'Analyzing...';
454
+ analyzeIcon.classList.add('hidden');
455
+ buttonSpinner.classList.remove('hidden');
456
+ analyzeButton.disabled = true;
457
+ } else {
458
+ analysisOverlay.classList.remove('visible');
459
+ buttonText.textContent = 'Analyze Location';
460
+ analyzeIcon.classList.remove('hidden');
461
+ buttonSpinner.classList.add('hidden');
462
+ analyzeButton.disabled = false;
463
+ }
464
+ }
465
+
466
+ function displayError(message, isWarning = false) {
467
+ errorText.innerHTML = message;
468
+ errorMessageContainer.classList.remove('hidden');
469
+ const errorIconEl = errorMessageContainer.querySelector('i');
470
+ const errorTitleEl = errorMessageContainer.querySelector('h3');
471
+
472
+ if (isWarning) {
473
+ errorMessageContainer.className = 'my-6 p-5 bg-yellow-50 border-l-4 border-yellow-500 text-yellow-700 rounded-md shadow-md flex';
474
+ if(errorIconEl) errorIconEl.className = 'icon-info text-2xl text-yellow-500';
475
+ if(errorTitleEl) errorTitleEl.textContent = "Notice";
476
+ } else {
477
+ errorMessageContainer.className = 'my-6 p-5 bg-red-50 border-l-4 border-red-500 text-red-700 rounded-md shadow-md flex';
478
+ if(errorIconEl) errorIconEl.className = 'icon-close text-2xl text-red-500';
479
+ if(errorTitleEl) errorTitleEl.textContent = "Analysis Error";
480
+ }
481
+ resultsSection.classList.add('hidden');
482
+ }
483
+ function hideError() { errorMessageContainer.classList.add('hidden'); }
484
+
485
+ async function handleAnalysis() {
486
+ const latitude = parseFloat(latitudeInput.value);
487
+ const longitude = parseFloat(longitudeInput.value);
488
+
489
+ if (isNaN(latitude) || isNaN(longitude) || latitude < -90 || latitude > 90 || longitude < -180 || longitude > 180) {
490
+ displayError("Valid latitude (-90 to 90) & longitude (-180 to 180) required."); return;
491
+ }
492
+
493
+ hideError(); showLoadingState(true); resultsSection.classList.add('hidden');
494
+
495
+ try {
496
+ const response = await fetch('/api/analyze_location', {
497
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ latitude, longitude })
498
+ });
499
+ const data = await response.json();
500
+
501
+ if (!response.ok) throw new Error(data.error_message || data.error || `Analysis failed: ${response.status}`);
502
+ if (data.error_message && response.ok && !data.safety_score) { // Check if it's a fallback error from backend
503
+ displayError(`<strong>Analysis Incomplete:</strong> ${data.error_message}<br>Some information may be missing or generalized. Please try a different location or refine your query.`, true);
504
+ }
505
+
506
+ resultsSection.classList.remove('hidden');
507
+ if (resultsMap) resultsMap.invalidateSize();
508
+
509
+ displayDetailedResults(data, latitude, longitude);
510
+ updateResultsMap(data, latitude, longitude);
511
+ setTimeout(() => {
512
+ const firstResultCard = resultsSection.querySelector('.card');
513
+ if (firstResultCard) {
514
+ firstResultCard.scrollIntoView({ behavior: 'smooth', block: 'start' });
515
+ }
516
+ }, 300);
517
+
518
+ } catch (error) {
519
+ console.error('Analysis error:', error);
520
+ displayError(error.message || "Unexpected error during analysis.");
521
+ } finally {
522
+ showLoadingState(false);
523
+ }
524
+ }
525
+
526
+ function getUserLocationAndAnalyze() {
527
+ if (!navigator.geolocation) { displayError("Geolocation not supported by this browser."); return; }
528
+
529
+ const originalButtonHTML = useMyLocationButton.innerHTML;
530
+ useMyLocationButton.innerHTML = `<div class="btn-spinner !ml-0 !mr-2"></div> Locating...`;
531
+ useMyLocationButton.disabled = true;
532
+
533
+ navigator.geolocation.getCurrentPosition(
534
+ position => {
535
+ const { latitude: lat, longitude: lon } = position.coords;
536
+ latitudeInput.value = lat.toFixed(6);
537
+ longitudeInput.value = lon.toFixed(6);
538
+ updateInputMarker(lat, lon);
539
+ locationQueryInput.value = '';
540
+ useMyLocationButton.innerHTML = originalButtonHTML;
541
+ useMyLocationButton.disabled = false;
542
+ handleAnalysis();
543
+ },
544
+ error => {
545
+ console.error("Geolocation error:", error);
546
+ displayError("Could not get current location. Check browser permissions.");
547
+ useMyLocationButton.innerHTML = originalButtonHTML;
548
+ useMyLocationButton.disabled = false;
549
+ },
550
+ { timeout: 10000, enableHighAccuracy: true }
551
+ );
552
+ }
553
+
554
+ function getRiskBadgeClasses(riskLevel) {
555
+ riskLevel = riskLevel ? String(riskLevel).toLowerCase().replace(/[\s-]+/g, "_") : 'not_assessed';
556
+ const classMap = { 'low': 'risk-low', 'negligible': 'risk-low', 'stable': 'risk-low', 'medium': 'risk-medium', 'moderately_stable': 'risk-medium', 'high': 'risk-high', 'very_high': 'risk-high', 'unstable': 'risk-high', 'not_assessed': 'risk-not_assessed', 'requires_investigation': 'risk-not_assessed', 'variable': 'risk-not_assessed' };
557
+ return classMap[riskLevel] || 'risk-not_assessed';
558
+ }
559
+
560
+ function formatRiskDetail(container, title, riskData) {
561
+ container.innerHTML = '';
562
+ if (!riskData || (riskData.level === undefined && riskData.type === undefined)) {
563
+ container.innerHTML = `<p class="text-sm text-gray-500">${title}: Data unavailable or not applicable.</p>`; return;
564
+ }
565
+ const level = riskData.level || riskData.type;
566
+ let detailsHTML = `<p class="text-sm text-gray-600 leading-relaxed">${riskData.details || 'No specific details provided.'}</p>`;
567
+ if (riskData.concerns && riskData.concerns.length > 0) {
568
+ detailsHTML += `<ul class="list-disc list-inside text-xs text-gray-500 mt-2 pl-3 space-y-1">`;
569
+ riskData.concerns.forEach(concern => detailsHTML += `<li>${concern}</li>`);
570
+ detailsHTML += `</ul>`;
571
+ }
572
+ container.innerHTML = `
573
+ <div class="flex justify-between items-center mb-1.5">
574
+ <strong class="text-md font-medium text-gray-700">${title}</strong>
575
+ <span class="risk-badge ${getRiskBadgeClasses(level)}">${String(level).replace(/_/g, ' ')}</span>
576
+ </div>
577
+ ${detailsHTML}
578
+ `;
579
+ }
580
+
581
+ function updateSafetyGauge(score) {
582
+ const meter = document.getElementById('score-gauge-meter-dynamic');
583
+ score = Math.max(0, Math.min(100, parseInt(score) || 0));
584
+ scoreValueDisplay.textContent = score;
585
+ const rotation = (score / 100) * 180;
586
+ meter.style.transform = `rotate(${rotation}deg)`;
587
+ if (score >= 70) scoreValueDisplay.style.color = '#047857';
588
+ else if (score >= 40) scoreValueDisplay.style.color = '#CA8A04';
589
+ else scoreValueDisplay.style.color = '#B91C1C';
590
+ }
591
+
592
+ function displayDetailedResults(data, lat, lon) {
593
+ locationNameDisplay.textContent = data.location_name || "Site Assessment";
594
+ currentCoordsDisplay.textContent = `Lat: ${lat.toFixed(4)}, Lon: ${lon.toFixed(4)}`;
595
+
596
+ updateSafetyGauge(data.safety_score || 0);
597
+ summaryAssessmentP.innerHTML = data.summary_assessment ? data.summary_assessment.replace(/\n/g, '<br>') : 'No summary provided.'; // Allow line breaks
598
+ suitabilityStatementP.textContent = data.suitability_statement || 'Suitability not determined.';
599
+
600
+ const suitability = String(data.suitability_statement || "").toLowerCase();
601
+ let badgeClass = "px-4 py-2 text-md font-semibold rounded-full self-start sm:self-center transition-all duration-300 ";
602
+ if (suitability.includes("suitable") || suitability.includes("recommended")) badgeClass += "bg-green-100 text-green-700 border border-green-300";
603
+ else if (suitability.includes("caution") || suitability.includes("concerns") || suitability.includes("mitigation")) badgeClass += "bg-yellow-100 text-yellow-700 border border-yellow-300";
604
+ else if (suitability.includes("not recommended") || suitability.includes("unsuitable") || suitability.includes("incomplete") || suitability.includes("major intervention")) badgeClass += "bg-red-100 text-red-700 border border-red-300";
605
+ else badgeClass += "bg-gray-100 text-gray-700 border border-gray-300";
606
+ suitabilityBadge.className = badgeClass;
607
+ suitabilityBadge.textContent = data.suitability_statement ? (data.suitability_statement.split(' ')[0] + (data.suitability_statement.split(' ')[1] ? ' ' + data.suitability_statement.split(' ')[1] : '')) : "Pending";
608
+
609
+
610
+ formatRiskDetail(earthquakeRiskDetailsDiv, 'Earthquake', data.geological_risks?.earthquake_risk);
611
+ formatRiskDetail(landslideRiskDetailsDiv, 'Landslide', data.geological_risks?.landslide_risk);
612
+ formatRiskDetail(soilStabilityDetailsDiv, 'Soil Stability', data.geological_risks?.soil_stability);
613
+
614
+ formatRiskDetail(floodRiskDetailsDiv, 'Flood', data.hydrological_risks?.flood_risk);
615
+ if (data.hydrological_risks?.tsunami_risk && data.hydrological_risks.tsunami_risk.level && data.hydrological_risks.tsunami_risk.level.toLowerCase() !== 'negligible') {
616
+ formatRiskDetail(tsunamiRiskDetailsDiv, 'Tsunami', data.hydrological_risks.tsunami_risk);
617
+ tsunamiRiskDetailsDiv.classList.remove('hidden');
618
+ } else { tsunamiRiskDetailsDiv.classList.add('hidden'); }
619
+
620
+ otherEnvRisksList.innerHTML = '';
621
+ if (data.other_environmental_risks && data.other_environmental_risks.length > 0) {
622
+ data.other_environmental_risks.forEach(risk => {
623
+ const riskDiv = document.createElement('div');
624
+ riskDiv.className = 'risk-detail-item';
625
+ formatRiskDetail(riskDiv, risk.type, risk);
626
+ otherEnvRisksList.appendChild(riskDiv);
627
+ });
628
+ otherEnvRisksAccordion.classList.remove('hidden');
629
+ } else { otherEnvRisksAccordion.classList.add('hidden'); }
630
+
631
+ updateList(keyRiskFactorsUl, data.key_risk_factors_summary, 'No specific key risk factors highlighted.');
632
+ updateList(mitigationRecommendationsUl, data.mitigation_recommendations, 'No specific mitigation strategies provided.');
633
+ updateList(furtherInvestigationsUl, data.further_investigations_needed, 'No specific further investigations suggested.');
634
+
635
+ altLocationsContainer.innerHTML = '';
636
+ if (data.alternative_locations_analysis && data.alternative_locations_analysis.length > 0) {
637
+ data.alternative_locations_analysis.forEach(alt => {
638
+ const card = document.createElement('div');
639
+ card.className = 'p-5 rounded-lg border border-gray-200 hover:shadow-xl transform hover:-translate-y-1 transition-all duration-300 cursor-pointer bg-white hover:border-blue-400';
640
+ let prosConsHTML = '';
641
+ if ((alt.potential_pros && alt.potential_pros.length > 0) || (alt.potential_cons && alt.potential_cons.length > 0)) {
642
+ prosConsHTML += '<div class="text-xs mt-3 pt-3 border-t border-gray-200 space-y-1.5">';
643
+ if (alt.potential_pros && alt.potential_pros.length) prosConsHTML += `<div><strong class="text-green-600">Pros:</strong> ${alt.potential_pros.join('; ')}</div>`;
644
+ if (alt.potential_cons && alt.potential_cons.length) prosConsHTML += `<div><strong class="text-red-600">Cons:</strong> ${alt.potential_cons.join('; ')}</div>`;
645
+ prosConsHTML += '</div>';
646
+ }
647
+ card.innerHTML = `
648
+ <div class="flex justify-between items-start mb-2">
649
+ <div>
650
+ <h4 class="font-semibold text-blue-600 text-lg">${alt.name_suggestion || 'Alternative Site'}</h4>
651
+ <p class="text-xs text-gray-500">${alt.actual_name || `Lat: ${parseFloat(alt.latitude).toFixed(3)}, Lon: ${parseFloat(alt.longitude).toFixed(3)}`}</p>
652
+ </div>
653
+ <span class="text-sm text-gray-500 whitespace-nowrap font-medium">${alt.estimated_distance_km} km</span>
654
+ </div>
655
+ <div class="text-md mb-2">Est. Safety Score: <strong class="${(alt.comparative_safety_score_estimate || 0) >= 70 ? 'text-green-700' : (alt.comparative_safety_score_estimate || 0) >= 40 ? 'text-yellow-700' : 'text-red-700'}">${alt.comparative_safety_score_estimate !== undefined ? alt.comparative_safety_score_estimate : 'N/A'}</strong></div>
656
+ <p class="text-sm text-gray-600 mb-2">${alt.brief_justification || 'General alternative suggestion.'}</p>
657
+ ${prosConsHTML}
658
+ `;
659
+ card.addEventListener('click', () => {
660
+ resultsMap.setView([parseFloat(alt.latitude), parseFloat(alt.longitude)], 14, {animate: true});
661
+ alternativeMarkers.forEach(m => {
662
+ const markerLatLng = m.getLatLng();
663
+ if (markerLatLng.lat.toFixed(4) === parseFloat(alt.latitude).toFixed(4) && markerLatLng.lng.toFixed(4) === parseFloat(alt.longitude).toFixed(4)) {
664
+ m.openPopup();
665
+ }
666
+ });
667
+ });
668
+ altLocationsContainer.appendChild(card);
669
+ });
670
+ altLocationsSection.classList.remove('hidden');
671
+ } else {
672
+ altLocationsContainer.innerHTML = '<p class="text-md text-gray-500">No significantly better alternative locations were identified based on the current analysis.</p>';
673
+ altLocationsSection.classList.remove('hidden');
674
+ }
675
+
676
+ dataConfidenceSpan.textContent = data.data_confidence_level || 'N/A';
677
+ disclaimerP.textContent = data.disclaimer || 'Standard disclaimers apply. Consult professionals.';
678
+ }
679
+
680
+ function updateList(listElement, items, emptyMessage) {
681
+ listElement.innerHTML = '';
682
+ if (items && items.length > 0) {
683
+ items.forEach(item => {
684
+ const li = document.createElement('li');
685
+ li.textContent = item;
686
+ listElement.appendChild(li);
687
+ });
688
+ } else {
689
+ const li = document.createElement('li');
690
+ li.textContent = emptyMessage;
691
+ li.className = "text-gray-500 italic";
692
+ listElement.appendChild(li);
693
+ }
694
+ }
695
+
696
+ function updateResultsMap(data, currentLat, currentLng) {
697
+ if (currentResultMarker) resultsMap.removeLayer(currentResultMarker);
698
+ alternativeMarkers.forEach(marker => resultsMap.removeLayer(marker));
699
+ alternativeMarkers.length = 0;
700
+
701
+ currentResultMarker = L.marker([currentLat, currentLng], { icon: primaryLocationIcon, zIndexOffset: 1000 })
702
+ .addTo(resultsMap)
703
+ .bindPopup(`<b>${data.location_name || 'Analyzed Location'}</b><br>Score: ${data.safety_score || 'N/A'}<br>${data.suitability_statement || ''}`)
704
+ .openPopup();
705
+
706
+ const bounds = L.latLngBounds([[currentLat, currentLng]]);
707
+
708
+ if (data.alternative_locations_analysis && data.alternative_locations_analysis.length > 0) {
709
+ data.alternative_locations_analysis.forEach(alt => {
710
+ try {
711
+ const altLat = parseFloat(alt.latitude); const altLng = parseFloat(alt.longitude);
712
+ if (isNaN(altLat) || isNaN(altLng)) { console.warn("Invalid alt coords:", alt); return; }
713
+ const icon = (alt.comparative_safety_score_estimate || 0) > (data.safety_score || 0) + 5 ? saferAlternativeIcon : otherAlternativeIcon;
714
+ const altMarker = L.marker([altLat, altLng], { icon: icon })
715
+ .addTo(resultsMap)
716
+ .bindPopup(`<b>${alt.name_suggestion || 'Alternative'}</b> (${alt.actual_name || ''})<br>Est. Score: ${alt.comparative_safety_score_estimate || 'N/A'}<br>${alt.estimated_distance_km} km away`);
717
+ alternativeMarkers.push(altMarker); bounds.extend([altLat, altLng]);
718
+ } catch (e) { console.error("Error creating alt marker:", alt, e); }
719
+ });
720
+ }
721
+
722
+ if (bounds.isValid() && !bounds.getSouthWest().equals(bounds.getNorthEast())) {
723
+ resultsMap.fitBounds(bounds, { padding: [60, 60], maxZoom: 14, animate: true });
724
+ } else { resultsMap.setView([currentLat, currentLng], 13, {animate: true}); }
725
+ }
726
+ </script>
727
+ </body>
728
+ </html>
templates/index1.html ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import requests
4
+ from flask import Flask, request, jsonify, send_from_directory
5
+ from flask_cors import CORS
6
+
7
+ # Configure Flask app
8
+ app = Flask(__name__, static_folder='.')
9
+ CORS(app) # Enable CORS for all origins
10
+
11
+ # --- Open-Meteo API Configuration ---
12
+ OPENMETEO_BASE_URL = "https://api.open-meteo.com/v1/forecast"
13
+
14
+ WEATHER_VARIABLES = [
15
+ "temperature_2m",
16
+ "relative_humidity_2m",
17
+ "precipitation",
18
+ "weathercode",
19
+ "windspeed_10m",
20
+ "windgusts_10m",
21
+ "pressure_msl"
22
+ ]
23
+
24
+ DAILY_VARIABLES = [
25
+ "precipitation_sum",
26
+ "temperature_2m_max",
27
+ "temperature_2m_min"
28
+ ]
29
+
30
+ # --- Data Fetching Functions ---
31
+
32
+ def get_weather_data(lat, lon):
33
+ """Fetches current and recent weather data from Open-Meteo."""
34
+ try:
35
+ params = {
36
+ "latitude": lat,
37
+ "longitude": lon,
38
+ "current": ",".join(WEATHER_VARIABLES),
39
+ "daily": ",".join(DAILY_VARIABLES),
40
+ "past_days": 1,
41
+ "timezone": "auto",
42
+ "forecast_days": 1
43
+ }
44
+ print(f"Fetching weather data for ({lat}, {lon})...")
45
+ response = requests.get(OPENMETEO_BASE_URL, params=params)
46
+ response.raise_for_status() # Raise an HTTPError for bad responses
47
+ data = response.json()
48
+ print("Weather data fetched successfully.")
49
+
50
+ current = data.get('current', {})
51
+ daily = data.get('daily', {})
52
+
53
+ weather_info = {
54
+ "source": "Open-Meteo API",
55
+ "latitude": data.get('latitude'),
56
+ "longitude": data.get('longitude'),
57
+ "temperature_celsius_current": current.get('temperature_2m'),
58
+ "temperature_celsius_max_daily": daily.get('temperature_2m_max', [None])[0],
59
+ "temperature_celsius_min_daily": daily.get('temperature_2m_min', [None])[0],
60
+ "humidity_percent_current": current.get('relative_humidity_2m'),
61
+ "precipitation_mm_current": current.get('precipitation'),
62
+ "precipitation_mm_past_24h": daily.get('precipitation_sum', [None])[0],
63
+ "windspeed_kmh_current": current.get('windspeed_10m'),
64
+ "windgusts_kmh_current": current.get('windgusts_10m'),
65
+ "pressure_hpa_current": current.get('pressure_msl'),
66
+ "weathercode_current": current.get('weathercode')
67
+ }
68
+ return weather_info
69
+
70
+ except requests.exceptions.RequestException as e:
71
+ print(f"Error fetching weather data: {e}")
72
+ return {"error": "Could not fetch weather data", "details": str(e)}
73
+ except Exception as e:
74
+ print(f"An unexpected error occurred while processing weather data: {e}")
75
+ return {"error": "An unexpected error occurred with weather data", "details": str(e)}
76
+
77
+
78
+ def get_non_weather_data_simulated(lat, lon):
79
+ """
80
+ Simulates getting non-weather data.
81
+ This is still simplified based on rough India geography.
82
+ """
83
+ lat = float(lat)
84
+ lon = float(lon)
85
+
86
+ data = {
87
+ "source": "Simulated/Inferred Data",
88
+ "latitude": lat,
89
+ "longitude": lon,
90
+ "elevation_meters": 50, # Base elevation
91
+ "proximity_to_coast_km": 800, # Base distance
92
+ "proximity_to_major_river_km": 200, # Base distance
93
+ "soil_type": "general",
94
+ "vegetation_density": "moderate",
95
+ "historical_disaster_frequency": "medium",
96
+ "population_density": "moderate"
97
+ }
98
+
99
+ # Adjust simulated data based on location approximations for India
100
+ if 8 <= lat <= 37 and 68 <= lon <= 97: # Basic India bounds
101
+ if lat > 28 or lon > 90: # Himalayan region, North East
102
+ data["elevation_meters"] = 1500 + max(0, lat - 28)*100 + max(0, lon - 90)*50
103
+ data["soil_type"] = "mountainous/hilly"
104
+ data["vegetation_density"] = "high"
105
+ data["historical_disaster_frequency"] = "high (Landslides, Earthquakes, Floods)"
106
+ data["proximity_to_major_river_km"] = min(data["proximity_to_major_river_km"], 10) if lat > 28 else data["proximity_to_major_river_km"]
107
+
108
+
109
+ if 15 <= lat <= 25 and 70 <= lon <= 85: # Central India, Deccan
110
+ data["elevation_meters"] = 500 + max(0, lat - 15)*30
111
+ data["soil_type"] = "black soil/plateau"
112
+ data["vegetation_density"] = "moderate to low"
113
+ data["historical_disaster_frequency"] = "medium (Droughts, Heatwaves, Wildfires)"
114
+ data["population_density"] = "moderate to high"
115
+
116
+ if lat < 22 and lon > 75: # South India, Coastal East/West
117
+ east_coast_dist = abs(lon - 82) * 111
118
+ west_coast_dist = abs(lon - 74) * 111
119
+ data["proximity_to_coast_km"] = min(east_coast_dist, west_coast_dist, data["proximity_to_coast_km"])
120
+ data["elevation_meters"] = 50 + max(0, (22-lat)*10)
121
+ data["soil_type"] = "coastal alluvial/laterite"
122
+ data["historical_disaster_frequency"] = "high (Cyclones, Floods, Heatwaves)"
123
+ data["population_density"] = "high"
124
+
125
+
126
+ if lat > 25 and lon < 80: # North India, Gangetic plains
127
+ data["elevation_meters"] = 50 + max(0, lat-25)*10
128
+ data["proximity_to_major_river_km"] = min(data["proximity_to_major_river_km"], 5)
129
+ data["soil_type"] = "alluvial"
130
+ data["historical_disaster_frequency"] = "high (Floods, Heatwaves, Droughts)"
131
+ data["population_density"] = "very high"
132
+
133
+ # Add some minor random variation
134
+ import random
135
+ data["elevation_meters"] = max(0, data["elevation_meters"] + random.randint(-10, 10))
136
+ data["proximity_to_coast_km"] = max(0, data["proximity_to_coast_km"] + random.randint(-20, 20))
137
+ data["proximity_to_major_river_km"] = max(0, data["proximity_to_major_river_km"] + random.randint(-5, 5))
138
+
139
+ return data
140
+
141
+ # --- Flask Routes ---
142
+
143
+ @app.route('/')
144
+ def index():
145
+ return send_from_directory('.', 'index.html')
146
+
147
+ # API endpoint to get location-based data (weather + simulated)
148
+ @app.route('/get_location_data', methods=['POST'])
149
+ def get_location_data():
150
+ data = request.get_json()
151
+ lat = data.get('lat')
152
+ lon = data.get('lon')
153
+
154
+ if lat is None or lon is None:
155
+ return jsonify({"error": "Latitude and Longitude are required"}), 400
156
+
157
+ try:
158
+ # Get real weather data
159
+ weather_data = get_weather_data(lat, lon)
160
+ if "error" in weather_data:
161
+ # If weather data fetch fails, return the error
162
+ return jsonify({"error": f"Failed to get weather data: {weather_data['details']}"}), 500
163
+
164
+ # Get simulated non-weather data
165
+ non_weather_data = get_non_weather_data_simulated(lat, lon)
166
+
167
+ # Combine all data
168
+ location_data = {
169
+ "latitude": lat,
170
+ "longitude": lon,
171
+ "weather_data": weather_data,
172
+ "non_weather_data": non_weather_data
173
+ }
174
+
175
+ # Return the combined data
176
+ return jsonify(location_data)
177
+
178
+ except Exception as e:
179
+ print(f"An error occurred while getting location data: {e}")
180
+ return jsonify({"error": f"An internal server error occurred: {str(e)}"}), 500
181
+
182
+ if __name__ == '__main__':
183
+ # Run the Flask app
184
+ # Change port if 5000 is in use
185
+ app.run(debug=True, port=5000)