import gradio as gr import requests def get_coordinates(city): """Get latitude and longitude from city name using OpenStreetMap Nominatim API.""" try: url = f"https://nominatim.openstreetmap.org/search?city={city}&format=json" response = requests.get(url, headers={"User-Agent": "weather-app"}) data = response.json() if not data: return None, None lat = float(data[0]["lat"]) lon = float(data[0]["lon"]) return lat, lon except: return None, None def get_weather(city): lat, lon = get_coordinates(city) if lat is None or lon is None: return "City not found. Please try again." try: url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}¤t_weather=true" response = requests.get(url) data = response.json() if "current_weather" not in data: return "Weather data not available." weather = data["current_weather"] temp = weather["temperature"] wind = weather["windspeed"] code = weather["weathercode"] # Simple mapping of weather codes weather_codes = { 0: "Clear sky", 1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast", 45: "Fog", 48: "Depositing rime fog", 51: "Light drizzle", 53: "Moderate drizzle", 55: "Dense drizzle", 61: "Slight rain", 63: "Moderate rain", 65: "Heavy rain", 71: "Slight snow fall", 73: "Moderate snow fall", 75: "Heavy snow fall", 80: "Rain showers", 81: "Moderate rain showers", 82: "Violent rain showers", } description = weather_codes.get(code, "Unknown") report = ( f"Weather in {city}:\n" f"Temperature: {temp}°C\n" f"Condition: {description}\n" f"Wind Speed: {wind} km/h" ) return report except Exception as e: return f"Error: {str(e)}" # Gradio UI 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)." ) if __name__ == "__main__": iface.launch()