Download app.py from MuhammadKhuram/Live_Weather_Application: direct link, hf CLI and curl.
- Browser
- Download file 2.18 kB
-
https://huggingface.co/spaces/MuhammadKhuram/Live_Weather_Application/resolve/main/app.py
- Command line
-
hf download hf://spaces/MuhammadKhuram/Live_Weather_Application/app.py
-
curl -L -o app.py https://huggingface.co/spaces/MuhammadKhuram/Live_Weather_Application/resolve/main/app.py
2.18 kB
| 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() |