muhammadfaheem34's picture
Create app.py
40cd83f verified
Raw History Blame Contribute Delete
3.93 kB
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}
![icon]({icon_url})
🌑 **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)