Weather / app.py
sairaishaq's picture
Create app.py
ff8da80 verified
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"&current_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()