Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import requests | |
| def get_weather(city: str): | |
| """Fetch weather forecast for a given city using Open-Meteo API""" | |
| try: | |
| # Step 1: Get latitude & longitude from Open-Meteo geocoding API | |
| geo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1" | |
| geo_response = requests.get(geo_url).json() | |
| if "results" not in geo_response: | |
| return f"β Could not find location: {city}" | |
| lat = geo_response["results"][0]["latitude"] | |
| lon = geo_response["results"][0]["longitude"] | |
| # Step 2: Get weather forecast | |
| weather_url = ( | |
| f"https://api.open-meteo.com/v1/forecast" | |
| f"?latitude={lat}&longitude={lon}" | |
| f"¤t_weather=true" | |
| ) | |
| weather_response = requests.get(weather_url).json() | |
| if "current_weather" not in weather_response: | |
| return "β Weather data not available." | |
| weather = weather_response["current_weather"] | |
| temp = weather["temperature"] | |
| wind = weather["windspeed"] | |
| desc = f"π‘ Temperature: {temp}Β°C\nπ¨ Windspeed: {wind} km/h" | |
| return f"π City: {city}\n{desc}" | |
| except Exception as e: | |
| return f"β οΈ Error: {str(e)}" | |
| # Gradio Interface | |
| iface = gr.Interface( | |
| fn=get_weather, | |
| inputs=gr.Textbox(label="Enter City Name"), | |
| outputs=gr.Textbox(label="Weather Forecast"), | |
| title="π€ Weather Forecast App", | |
| description="Enter a city name to get the current weather forecast (powered by Open-Meteo API).", | |
| ) | |
| if __name__ == "__main__": | |
| iface.launch() | |