Spaces:
Sleeping
Sleeping
| 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']}" | |
| ) |