File size: 2,126 Bytes
790625d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import httpx
from typing import Tuple, Optional
import logging
from core.logging_config import get_logger

# Initialize logger
logger = get_logger(__name__)

class GeocodingResult:
    def __init__(self, success: bool, lat: Optional[float] = None, lon: Optional[float] = None, error: Optional[str] = None):
        self.success: bool = success
        self.lat: Optional[float] = lat
        self.lon: Optional[float] = lon
        self.error: Optional[str] = error
    
    def to_tuple(self) -> Tuple[str, str]:
        """Convert to (lat, lon) strings for Gradio compatibility"""
        if self.success:
            return str(self.lat), str(self.lon)
        return "Not found", "Not found"

def geocode_location(location: str) -> GeocodingResult:
    """
    Unified geocoding service with proper error handling.
    Replaces both geocode_city functions from app_logic.py and res_test.py
    """
    if not location or not location.strip():
        logger.warning("Empty location provided for geocoding")
        return GeocodingResult(False, error="Empty location provided")
    
    logger.info(f"Attempting to geocode location: {location}")
    
    try:
        with httpx.Client() as client:
            url = f"https://nominatim.openstreetmap.org/search?q={location}&format=json&limit=1&addressdetails=1"
            headers = {"User-Agent": "Maguclock_MCP/1.0"}
            response = client.get(url, headers=headers)
            response.raise_for_status()
            data = response.json()
            
            if data:
                lat = float(data[0]["lat"])
                lon = float(data[0]["lon"])
                logger.info(f"Successfully geocoded {location} to lat: {lat}, lon: {lon}")
                return GeocodingResult(True, lat, lon)
            else:
                logger.warning(f"Location not found: {location}")
                return GeocodingResult(False, error="Location not found")
                
    except Exception as e:
        logger.error(f"Geocoding error for location '{location}': {str(e)}")
        return GeocodingResult(False, error=f"Geocoding error: {str(e)}")