File size: 2,794 Bytes
1d79f77 | 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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | 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("""
<style>
body {
background: linear-gradient(135deg, #1e3c72, #2a5298);
color: white;
}
.main {
background: transparent;
}
.stTextInput>div>div>input {
border-radius: 10px;
}
.stButton button {
border-radius: 10px;
background-color: #00c6ff;
color: white;
}
</style>
""", 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"""
<div style='background: rgba(255,255,255,0.1); padding:10px; border-radius:10px; text-align:center'>
<b>{data['dt_txt'].split()[0]}</b><br>
π‘ {data['main']['temp']}Β°C<br>
β {data['weather'][0]['main']}
</div>
""", 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() |