import requests import json import os from datetime import datetime, timedelta import re import pytz def parse_geonet_title(title): match = re.search(r'\d+\skm\s(north|south|west|east|north-east|north-west|south-east|south-west|of)?\s*(.*)', title) if match: location = match.group(2).strip() location = location.replace('region', '').strip() return location if location else "Unknown Location" match = re.match(r'M\s\d+\.?\d*,\s*(.*)', title) if match: location = match.group(1).strip() location = location.replace('region', '').strip() return location if location else "Unknown Location" return title def get_earthquakes(min_mmi=8, limit=20, from_today_only=True): url = "https://api.geonet.org.nz/quakes/services/quake/" try: response = requests.get(url) response.raise_for_status() data = response.json() all_quakes = [] utc_timezone = pytz.utc nzt_timezone = pytz.timezone('Pacific/Auckland') current_nzt_date = datetime.now(nzt_timezone).date() for feature in data.get('features', []): props = feature.get('properties', {}) mmi = props.get('mmi') time_utc_ms = props.get('time') status = props.get('status', 'latest') quake_id = feature.get('id') if time_utc_ms is None: continue dt_object_utc_aware = utc_timezone.localize(datetime.fromtimestamp(time_utc_ms / 1000)) dt_object_nzt = dt_object_utc_aware.astimezone(nzt_timezone) if from_today_only: if dt_object_nzt.date() != current_nzt_date: continue if status != 'deleted': if mmi is None or mmi < min_mmi: continue title = props.get('title', 'Unknown Event') time_str = dt_object_nzt.strftime("%d - %b - %Y %I:%M %p %z") location = parse_geonet_title(title) all_quakes.append({ 'mmi': mmi, 'magnitude': props.get('magnitude'), 'depth': props.get('depth'), 'location': location, 'time': time_str, 'id': quake_id, 'utc_timestamp': time_utc_ms, 'status': status }) all_quakes.sort(key=lambda x: x['utc_timestamp'], reverse=True) return all_quakes[:limit] except requests.exceptioins.RequestException as e: print(f"Error fetching data from Geonet API: {e}") return [] def generate_html(quakes, output_file="geonet_earthquakes.html", css_file="style.css"): html_content = f"""