import streamlit as st
import requests
# Your OpenWeatherMap API key
API_KEY = "bb7a7d944437ed1b8df2a27b54490cbb"
# Function to fetch weather data
def get_weather(api_key, city):
try:
# Get the city's latitude and longitude
geocode_url = f"http://api.openweathermap.org/geo/1.0/direct?q={city}&limit=1&appid={api_key}"
geocode_response = requests.get(geocode_url).json()
if not geocode_response:
return None
lat = geocode_response[0]["lat"]
lon = geocode_response[0]["lon"]
# Get the current weather
url = f"http://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={api_key}&units=metric"
response = requests.get(url)
weather_data = response.json()
if response.status_code != 200:
return None
return weather_data
except Exception as e:
st.error(f"An error occurred: {e}")
return None
# Function to check for extreme weather
def check_extreme_weather(temp):
if temp < 0 or temp > 35:
return True
return False
# Streamlit app layout
st.set_page_config(page_title="Current Weather", page_icon=":cloud:", layout="wide")
# Background image
st.markdown("""
<style>
.reportview-container {
background: url('https://source.unsplash.com/1600x900/?weather') no-repeat center center fixed;
background-size: cover;
}
.sidebar .sidebar-content {
background: rgba(255, 255, 255, 0.8);
}
</style>
""", unsafe_allow_html=True)
st.title("Current Weather")
st.subheader("Enter the city name to get the current weather")
city = st.text_input("City Name", placeholder="e.g., Johannesburg")
if city:
st.spinner("Fetching weather data...")
weather_data = get_weather(API_KEY, city)
if weather_data:
temp = weather_data["main"]["temp"]
weather_desc = weather_data["weather"][0]["description"].capitalize()
icon = weather_data["weather"][0]["icon"]
city_name = weather_data["name"]
country = weather_data["sys"]["country"]
# Display weather information
col1, col2 = st.columns(2)
with col1:
st.image(f"http://openweathermap.org/img/wn/{icon}.png", width=100)
with col2:
st.header(f"{city_name}, {country}")
st.subheader(f"Temperature: {temp}°C")
st.write(f"Weather: {weather_desc}")
if check_extreme_weather(temp):
st.warning("Extreme weather alert!")
else:
st.error("City not found or invalid API key")