| import streamlit as st |
| import requests |
| import geocoder |
|
|
| |
| import os |
| API_KEY = os.getenv("API_KEY") |
| |
| 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 |
|
|
|
|
| |
| st.set_page_config(page_title="π¦ Smart Weather App", layout="centered") |
|
|
| |
| 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") |
|
|
| |
| if "city" not in st.session_state: |
| st.session_state.city = "Lahore" |
|
|
| |
| 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 |
|
|
| |
| 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']) |
|
|
| |
| 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() |
|
|
| |
| if new_city: |
| st.session_state.city = new_city |
| st.rerun() |