decodingdatascience's picture
Create app.py
459dd14 verified
import os
import requests
import gradio as gr
# ----------------------------------------
# 1) Read API key from Hugging Face secret
# (set OPENWEATHER_API_KEY in Space settings)
# ----------------------------------------
API_KEY = os.getenv("OPENWEATHER_API_KEY")
def get_weather(city: str) -> str:
"""Fetch weather for a given city using OpenWeatherMap API."""
if not city:
return "Please enter a city name."
if not API_KEY:
return "API key is not configured. Please contact the app owner."
url = (
"https://api.openweathermap.org/data/2.5/weather"
f"?q={city}&appid={API_KEY}&units=metric"
)
try:
response = requests.get(url, timeout=10)
data = response.json()
# Handle API error (e.g., city not found)
if data.get("cod") != 200:
message = data.get("message", "Unable to fetch weather data.")
return f"Error: {message.capitalize()}"
temp = data["main"]["temp"]
description = data["weather"][0]["description"]
return f"The current temperature in {city.title()} is {temp}°C with {description}."
except requests.exceptions.RequestException as e:
return f"Network error: {e}"
# ----------------------------------------
# 2) Gradio interface
# ----------------------------------------
iface = gr.Interface(
fn=get_weather,
inputs=gr.Textbox(label="City", placeholder="e.g., Abu Dhabi"),
outputs=gr.Textbox(label="Weather Info"),
title="Arshad Weather App",
description="Enter a city name to get current weather using OpenWeatherMap.",
)
# Hugging Face Spaces will run this
if __name__ == "__main__":
iface.launch()