Spaces:
Sleeping
Sleeping
File size: 3,926 Bytes
40cd83f | 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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | import gradio as gr
import requests
# ==============================
# π API KEY (ADD YOUR KEY HERE)
# ==============================
API_KEY = "b58b4fa298fca72bc2438258de81bb6a"
# ==============================
# π€ GET CURRENT WEATHER
# ==============================
def get_current_weather(city, unit):
try:
units = "metric" if unit == "Celsius" else "imperial"
url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units={units}"
response = requests.get(url, timeout=10)
data = response.json()
# β Error Handling
if data.get("cod") != 200:
return f"β Error: {data.get('message')}"
# β
Extract Data
name = data["name"]
country = data["sys"]["country"]
temp = data["main"]["temp"]
feels_like = data["main"]["feels_like"]
humidity = data["main"]["humidity"]
weather = data["weather"][0]["description"]
wind = data["wind"]["speed"]
icon = data["weather"][0]["icon"]
icon_url = f"http://openweathermap.org/img/wn/{icon}@2x.png"
unit_symbol = "Β°C" if unit == "Celsius" else "Β°F"
# π¨ UI Output
result = f"""
### π {name}, {country}

π‘ **Temperature:** {temp}{unit_symbol}
π€ **Feels Like:** {feels_like}{unit_symbol}
π§ **Humidity:** {humidity}%
π¬ **Wind Speed:** {wind} m/s
β **Condition:** {weather}
"""
return result
except requests.exceptions.Timeout:
return "β Request timed out. Try again."
except requests.exceptions.ConnectionError:
return "β Network error. Check your internet."
except Exception as e:
return f"β Unexpected error: {str(e)}"
# ==============================
# π
5-DAY FORECAST
# ==============================
def get_forecast(city, unit):
try:
units = "metric" if unit == "Celsius" else "imperial"
url = f"https://api.openweathermap.org/data/2.5/forecast?q={city}&appid={API_KEY}&units={units}"
response = requests.get(url, timeout=10)
data = response.json()
if data.get("cod") != "200":
return f"β Error: {data.get('message')}"
forecast_text = "### π
5-Day Forecast\n\n"
unit_symbol = "Β°C" if unit == "Celsius" else "Β°F"
# Show every 8th entry (~24 hours)
for i in range(0, len(data["list"]), 8):
item = data["list"][i]
date = item["dt_txt"]
temp = item["main"]["temp"]
desc = item["weather"][0]["description"]
forecast_text += f"π **{date}**\nπ‘ {temp}{unit_symbol} | β {desc}\n\n"
return forecast_text
except Exception as e:
return f"β Forecast error: {str(e)}"
# ==============================
# π MAIN FUNCTION
# ==============================
def weather_app(city, unit):
if not city.strip():
return "β Please enter a city name.", ""
current = get_current_weather(city, unit)
forecast = get_forecast(city, unit)
return current, forecast
# ==============================
# π¨ GRADIO UI
# ==============================
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("# π€ Weather App")
gr.Markdown("Enter a city name to get real-time weather and forecast")
with gr.Row():
city_input = gr.Textbox(label="π City Name", placeholder="e.g. Karachi")
unit_input = gr.Radio(["Celsius", "Fahrenheit"], value="Celsius", label="π‘ Unit")
submit_btn = gr.Button("π Get Weather")
with gr.Row():
current_output = gr.Markdown()
forecast_output = gr.Markdown()
# Loading feedback
submit_btn.click(
fn=weather_app,
inputs=[city_input, unit_input],
outputs=[current_output, forecast_output]
)
# π Launch (Colab Compatible)
demo.launch(share=True) |