File size: 2,549 Bytes
374cabb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# weatherr.py

import requests
import os
from dotenv import load_dotenv
load_dotenv()

# Replace with your API keys
OPENCAGE_API_KEY = os.getenv("OPENCAGE_API_KEY")
OPENWEATHER_API_KEY = os.getenv("OPENWEATHER_API_KEY")

def get_weather(

    latitude: float = None,

    longitude: float = None,

    address: str = None,

    district: str = None,

    state: str = None,

    units: str = "metric"  # "metric" or "imperial"

) -> dict:
    """

    Fetch current weather using coordinates or location name (address/district/state).



    Returns structured weather info from OpenWeatherMap.

    """
    # Step 1: Determine coordinates
    if latitude is None or longitude is None:
        if address:
            query = address
        elif district and state:
            query = f"{district}, {state}"
        elif district:
            query = district
        else:
            return {"error": "Provide either coordinates or location name (address/district+state)."}

        # Use OpenCageData geocoding
        geocode_url = "https://api.opencagedata.com/geocode/v1/json"
        params = {
            "q": query,
            "key": OPENCAGE_API_KEY,
            "limit": 1,
            "no_annotations": 1
        }
        try:
            resp = requests.get(geocode_url, params=params, timeout=10)
            resp.raise_for_status()
            data = resp.json()
            if data["results"]:
                latitude = data["results"][0]["geometry"]["lat"]
                longitude = data["results"][0]["geometry"]["lng"]
            else:
                return {"error": f"Location not found: {query}"}
        except Exception as e:
            return {"error": f"Geocoding error: {e}"}

    # Step 2: Fetch weather from OpenWeatherMap
    weather_url = "https://api.openweathermap.org/data/2.5/weather"
    params = {
        "lat": latitude,
        "lon": longitude,
        "appid": OPENWEATHER_API_KEY,
        "units": units
    }

    try:
        resp = requests.get(weather_url, params=params, timeout=10)
        resp.raise_for_status()
        return {"success": True, "data": resp.json()}
    except Exception as e:
        return {"error": f"Weather API error: {e}"}

# Example usage:
if __name__ == "__main__":
    res = get_weather(district="Bilaspur", state="Chhattisgarh")
    res2 = get_weather(latitude=22.0934, longitude=82.1564)
    res3 = get_weather(address="Bilaspur, Chhattisgarh")
    print(res)
    print(res2)
    print(res3)