Spaces:
Sleeping
Sleeping
File size: 1,819 Bytes
f739919 4906a14 f739919 4906a14 f739919 4906a14 f739919 | 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 | 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']}"
) |