Spaces:
Sleeping
Sleeping
File size: 2,454 Bytes
214b781 67b927d 214b781 67b927d 214b781 67b927d 214b781 67b927d 214b781 67b927d 214b781 67b927d 214b781 67b927d 214b781 67b927d 214b781 67b927d 214b781 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | 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()
|