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 # -------- PAGE CONFIG -------- st.set_page_config(page_title="🌦 Smart Weather App", layout="centered") # -------- CUSTOM CSS (ENGAGING BACKGROUND) -------- st.markdown(""" """, unsafe_allow_html=True) st.title("🌦 Smart Weather App") # -------- SESSION STATE -------- if "city" not in st.session_state: st.session_state.city = "Lahore" # default city # -------- WEEK FORECAST (TOP) -------- city = st.session_state.city forecast = get_forecast(city) if forecast.get("cod") == "200": st.subheader(f"📅 Weekly Forecast - {city}") cols = st.columns(5) index = 0 for i in range(0, 40, 8): data = forecast['list'][i] with cols[index % 5]: st.markdown(f"""
{data['dt_txt'].split()[0]}
🌡 {data['main']['temp']}°C
☁ {data['weather'][0]['main']}
""", unsafe_allow_html=True) index += 1 # -------- CURRENT WEATHER -------- weather = get_weather(city) if weather.get("cod") == 200: st.subheader("🌍 Current Weather") col1, col2, col3 = st.columns(3) col1.metric("🌡 Temp", f"{weather['main']['temp']} °C") col2.metric("💧 Humidity", f"{weather['main']['humidity']} %") col3.metric("🌥 Condition", weather['weather'][0]['main']) # -------- SEARCH BAR (BOTTOM) -------- st.markdown("---") st.subheader("🔍 Search City") col1, col2 = st.columns([3,1]) with col1: new_city = st.text_input("Enter city name", "") with col2: if st.button("📍 Auto"): detected = get_location() if detected: st.session_state.city = detected st.rerun() # Manual search if new_city: st.session_state.city = new_city st.rerun()