File size: 2,184 Bytes
4294820
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import requests
import os

def get_weather(city):
    # 1. Fetch the API key securely
    api_key = os.environ.get("WEATHER_API_KEY")
    
    if not api_key:
        return "⚠️ Error: WEATHER_API_KEY is not set. Please add it to your secrets."
    
    if not city.strip():
        return "⚠️ Please enter a valid city name."

    # 2. Construct the API Request URL
    # We use units=metric for Celsius. Change to units=imperial for Fahrenheit.
    base_url = "http://api.openweathermap.org/data/2.5/weather"
    params = {
        "q": city,
        "appid": api_key,
        "units": "metric" 
    }
    
    try:
        # 3. Call the API
        response = requests.get(base_url, params=params)
        data = response.json()
        
        # 4. Handle errors (like misspelling a city name)
        if data.get("cod") != 200:
            return f"❌ Error: {data.get('message', 'City not found').capitalize()}"
            
        # 5. Extract the weather data
        city_name = data["name"]
        country = data["sys"]["country"]
        temp = data["main"]["temp"]
        feels_like = data["main"]["feels_like"]
        humidity = data["main"]["humidity"]
        description = data["weather"][0]["description"].title()
        wind_speed = data["wind"]["speed"]
        
        # 6. Format the output nicely using Markdown
        report = f"""
### 🌍 Weather in {city_name}, {country}
* **🌡️ Temperature:** {temp}°C (Feels like {feels_like}°C)
* **💧 Humidity:** {humidity}%
* **☁️ Condition:** {description}
* **💨 Wind Speed:** {wind_speed} m/s
        """
        return report
        
    except Exception as e:
        return f"⚠️ An error occurred: {str(e)}"

# 7. Build the Gradio UI
demo = gr.Interface(
    fn=get_weather,
    inputs=gr.Textbox(label="Enter City Name", placeholder="e.g., London, Tokyo, New York..."),
    outputs=gr.Markdown(label="Live Weather Report"),
    title="🌤️ Live Weather App",
    description="Enter any city name to get real-time temperature, humidity, and weather conditions.",
    theme=gr.themes.Soft()
)

# Launch the app
if __name__ == "__main__":
    demo.launch()