Spaces:
Sleeping
Sleeping
Download app.py from raheeelarif86/Weather_App: direct link, hf CLI and curl.
- Browser
- Download file 1.65 kB
-
https://huggingface.co/spaces/raheeelarif86/Weather_App/resolve/main/app.py
- Command line
-
hf download hf://spaces/raheeelarif86/Weather_App/app.py
-
curl -L -o app.py https://huggingface.co/spaces/raheeelarif86/Weather_App/resolve/main/app.py
1.65 kB
| 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} is {temp}°C with {description}." | |
| except requests.exceptions.RequestException as e: | |
| return f"Network or API error: {e}" | |
| except KeyError: | |
| return "Error: Could not parse weather data. City might not be found." | |
| # Create and launch the Gradio interface | |
| iface = gr.Interface(fn=get_weather, inputs="text", outputs="text", | |
| title="OpenWeatherMap Weather App", | |
| description="Enter a city name to get current weather information.") | |
| if __name__ == "__main__": | |
| iface.launch(share=True) | |