Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import requests | |
| import os | |
| # π Use environment variable for API key (important for Hugging Face) | |
| API_KEY = os.getenv("Weather") | |
| def get_weather(city): | |
| if not city: | |
| return "β Please enter a city name" | |
| if not API_KEY: | |
| return "β API key not set" | |
| url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric" | |
| try: | |
| response = requests.get(url) | |
| data = response.json() | |
| if str(data.get("cod")) == "200": | |
| temp = data["main"]["temp"] | |
| humidity = data["main"]["humidity"] | |
| desc = data["weather"][0]["description"] | |
| country = data["sys"]["country"] | |
| return f""" | |
| π City: {city}, {country} | |
| π‘οΈ Temperature: {temp} Β°C | |
| π§ Humidity: {humidity}% | |
| π€οΈ Condition: {desc} | |
| """ | |
| else: | |
| return f"β Error: {data.get('message', 'Unknown error')}" | |
| except Exception as e: | |
| return f"β οΈ Network Error: {str(e)}" | |
| # π Gradio UI | |
| demo = gr.Interface( | |
| fn=get_weather, | |
| inputs=gr.Textbox(label="Enter City Name"), | |
| outputs=gr.Textbox(label="Weather Info"), | |
| title="π¦οΈ Weather App", | |
| description="Get real-time weather using OpenWeather API" | |
| ) | |
| # π Launch (for Hugging Face) | |
| demo.launch() |