ForcastWeather / app.py
0o7Hunk's picture
Update app.py
4906a14 verified
import streamlit as st
import requests
import geocoder
# πŸ‘‰ Put your API key here
import os
API_KEY = os.getenv("API_KEY")
# -------- FUNCTIONS --------
def get_weather(city):
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric"
return requests.get(url).json()
def get_forecast(city):
url = f"http://api.openweathermap.org/data/2.5/forecast?q={city}&appid={API_KEY}&units=metric"
return requests.get(url).json()
def get_location():
g = geocoder.ip('me')
return g.city
# -------- UI --------
st.set_page_config(page_title="🌦 Weather App", layout="centered")
st.title("🌦 Smart Weather App")
# Auto location
if st.button("πŸ“ Use My Location"):
city = get_location()
st.success(f"Detected City: {city}")
else:
city = ""
# Manual input (voice removed because HF doesn't support mic well)
city = st.text_input("Enter City Name", city)
# Weather
if city:
weather = get_weather(city)
if weather.get("cod") == 401:
st.error("❌ Invalid API Key")
elif weather.get("cod") == "404":
st.error("❌ City not found")
elif weather.get("cod") != 200:
st.error(f"Error: {weather.get('message')}")
else:
st.subheader(f"πŸ“ Weather in {city}")
st.metric("🌑 Temperature", f"{weather['main']['temp']} °C")
st.metric("πŸ’§ Humidity", f"{weather['main']['humidity']} %")
st.write(f"πŸŒ₯ Condition: {weather['weather'][0]['description']}")
# Forecast
st.subheader("πŸ“… 5-Day Forecast")
forecast = get_forecast(city)
for i in range(0, 40, 8):
data = forecast['list'][i]
st.write(
f"πŸ“† {data['dt_txt']} | 🌑 {data['main']['temp']}Β°C | {data['weather'][0]['description']}"
)