File size: 1,615 Bytes
ff8da80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import requests

def get_weather(city: str):
    """Fetch weather forecast for a given city using Open-Meteo API"""
    try:
        # Step 1: Get latitude & longitude from Open-Meteo geocoding API
        geo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1"
        geo_response = requests.get(geo_url).json()

        if "results" not in geo_response:
            return f"❌ Could not find location: {city}"

        lat = geo_response["results"][0]["latitude"]
        lon = geo_response["results"][0]["longitude"]

        # Step 2: Get weather forecast
        weather_url = (
            f"https://api.open-meteo.com/v1/forecast"
            f"?latitude={lat}&longitude={lon}"
            f"&current_weather=true"
        )
        weather_response = requests.get(weather_url).json()

        if "current_weather" not in weather_response:
            return "❌ Weather data not available."

        weather = weather_response["current_weather"]
        temp = weather["temperature"]
        wind = weather["windspeed"]
        desc = f"🌡 Temperature: {temp}°C\n💨 Windspeed: {wind} km/h"

        return f"📍 City: {city}\n{desc}"

    except Exception as e:
        return f"⚠️ Error: {str(e)}"

# Gradio Interface
iface = gr.Interface(
    fn=get_weather,
    inputs=gr.Textbox(label="Enter City Name"),
    outputs=gr.Textbox(label="Weather Forecast"),
    title="🌤 Weather Forecast App",
    description="Enter a city name to get the current weather forecast (powered by Open-Meteo API).",
)

if __name__ == "__main__":
    iface.launch()