import os import requests import streamlit as st from dotenv import load_dotenv def get_weather(city): """Fetch weather data from OpenWeatherMap API""" load_dotenv() api_key = os.getenv('OPENWEATHER_API_KEY') if not api_key: st.error("⚠️ OpenWeather API key not found. Please set OPENWEATHER_API_KEY in your environment variables.") return None base_url = "http://api.openweathermap.org/data/2.5/weather" params = { 'q': city, 'appid': api_key, 'units': 'imperial' } try: response = requests.get(base_url, params=params) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: st.error(f"Error fetching weather data: {e}") return None def display_weather(weather_data): """Display formatted weather information in Streamlit""" if not weather_data: return if 'main' not in weather_data: st.error("Invalid response from weather API. Please check the city name.") return temp_fahrenheit = weather_data['main']['temp'] feels_like = weather_data['main']['feels_like'] humidity = weather_data['main']['humidity'] description = weather_data['weather'][0]['description'].title() city_name = weather_data['name'] country = weather_data['sys']['country'] # Display weather report using Streamlit components st.success(f"Weather data retrieved for {city_name}, {country}") col1, col2, col3 = st.columns(3) with col1: st.metric("🌡️ Temperature", f"{temp_fahrenheit}°F", f"Feels like {feels_like}°F") with col2: st.metric("💧 Humidity", f"{humidity}%") with col3: st.metric("☁️ Condition", description) def main(): """Main application function""" st.set_page_config( page_title="Weather App", page_icon="🌤️", layout="wide" ) st.title("🌤️ Weather CLI App") st.markdown("Get current weather information for any city!") # Create input form with st.form("weather_form"): city = st.text_input("🏙️ Enter a city name:", placeholder="e.g., London, Tokyo, New York") submit_button = st.form_submit_button("Get Weather") if submit_button and city: with st.spinner(f"🔍 Fetching weather data for {city}..."): weather_data = get_weather(city.strip()) display_weather(weather_data) elif submit_button and not city: st.warning("Please enter a city name!") if __name__ == "__main__": main()