import requests import time import socket class SystemMonitor: _region_cache = None _engine_version = "AutoAlt Neural v2" @staticmethod def get_region(): """ Fetches the server's current region/city using a GeoIP service. Cached for the lifetime of the application to avoid rate limits. """ if SystemMonitor._region_cache: return SystemMonitor._region_cache try: # high-performance, free GeoIP API response = requests.get("http://ip-api.com/json", timeout=3) if response.status_code == 200: data = response.json() # User example showed "Frankfurt", which is a city. # We can combine City, Country for clarity or just City. city = data.get("city", "Unknown") country = data.get("countryCode", "") # Check for cloud provider hints in ISP if needed, but City is usually what people mean by 'Region' in this context region = f"{city}, {country}" if country else city SystemMonitor._region_cache = region return region except Exception as e: print(f"Region detection failed: {e}") return "Unknown (Network Restricted)" return "Unknown" @staticmethod def get_latency(target_url=None): """ Calculates the system's network latency by timing a request to a reliable backbone or specific target. Returns latency in milliseconds (int). """ # Default to the user's preferred check URL if no specific domain is given url_to_check = target_url if target_url else "https://dev.autoalt.ai/" try: # Measure reliable external connection time start = time.time() # Fast HEAD request requests.head(url_to_check, timeout=3) end = time.time() # Convert to ms and round latency_ms = int((end - start) * 1000) return latency_ms except Exception: # Retry with a socket method if HTTP fails (only for default check) if not target_url: try: start = time.time() socket.create_connection(("8.8.8.8", 53), timeout=2) end = time.time() return int((end - start) * 1000) except: return 999 return 999 # High latency/timeout indicator @staticmethod def get_status(target_url=None): """ Simple self-diagnostic status. """ # If we can reach external network, we are operational. latency = SystemMonitor.get_latency(target_url) if latency < 999: return "operational" return "degraded_connectivity" @staticmethod def get_system_stats(target_url=None): return { "region": SystemMonitor.get_region(), "latency": SystemMonitor.get_latency(target_url), "status": SystemMonitor.get_status(target_url), "engine": SystemMonitor._engine_version }