File size: 1,699 Bytes
459dd14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import requests
import gradio as gr

# ----------------------------------------
# 1) Read API key from Hugging Face secret
#    (set OPENWEATHER_API_KEY in Space settings)
# ----------------------------------------
API_KEY = os.getenv("OPENWEATHER_API_KEY")

def get_weather(city: str) -> str:
    """Fetch weather for a given city using OpenWeatherMap API."""
    if not city:
        return "Please enter a city name."

    if not API_KEY:
        return "API key is not configured. Please contact the app owner."

    url = (
        "https://api.openweathermap.org/data/2.5/weather"
        f"?q={city}&appid={API_KEY}&units=metric"
    )

    try:
        response = requests.get(url, timeout=10)
        data = response.json()

        # Handle API error (e.g., city not found)
        if data.get("cod") != 200:
            message = data.get("message", "Unable to fetch weather data.")
            return f"Error: {message.capitalize()}"

        temp = data["main"]["temp"]
        description = data["weather"][0]["description"]

        return f"The current temperature in {city.title()} is {temp}°C with {description}."

    except requests.exceptions.RequestException as e:
        return f"Network error: {e}"

# ----------------------------------------
# 2) Gradio interface
# ----------------------------------------
iface = gr.Interface(
    fn=get_weather,
    inputs=gr.Textbox(label="City", placeholder="e.g., Abu Dhabi"),
    outputs=gr.Textbox(label="Weather Info"),
    title="Arshad Weather App",
    description="Enter a city name to get current weather using OpenWeatherMap.",
)

# Hugging Face Spaces will run this
if __name__ == "__main__":
    iface.launch()