# app.py import os import requests from datetime import datetime import gradio as gr from openai import OpenAI # Load secrets from Hugging Face environment openai_api_key = os.getenv("OPENAI_API_KEY") weather_api_key = os.getenv("WEATHER_API_KEY") client = OpenAI(api_key=openai_api_key) top_cities = ["New York", "London", "Tokyo", "Paris", "Dubai", "Singapore", "Sydney", "Toronto", "Mumbai", "Berlin"] def get_weather(city_name): url = "http://api.openweathermap.org/data/2.5/weather" params = {"q": city_name, "appid": weather_api_key, "units": "metric"} response = requests.get(url, params=params) data = response.json() if response.status_code == 200: return data["main"]["temp"], data["weather"][0]["description"], data["coord"]["lat"], data["coord"]["lon"] return None, None, None, None def get_air_quality(lat, lon): url = "http://api.openweathermap.org/data/2.5/air_pollution" params = {"lat": lat, "lon": lon, "appid": weather_api_key} response = requests.get(url, params=params) data = response.json() if response.status_code == 200: aqi = data["list"][0]["main"]["aqi"] levels = {1: "Good 😊", 2: "Fair 🙂", 3: "Moderate 😐", 4: "Poor 😷", 5: "Very Poor 😫"} return f"Air Quality Index: {aqi} ({levels.get(aqi, 'Unknown')})" return "❌ Could not retrieve air quality info." def weather_chat(city, custom_city, user_query): selected_city = custom_city if custom_city else city temp, condition, lat, lon = get_weather(selected_city) if temp is None: return f"❌ Could not fetch weather for '{selected_city}'." report = f"The current temperature in {selected_city} is {temp}°C with {condition}." hour = datetime.now().hour time_context = "morning" if hour < 12 else "afternoon" if hour < 17 else "evening" alert = "⚠️ You may want to postpone any outdoor events." if "rain" in condition or "storm" in condition else "" aqi_info = get_air_quality(lat, lon) messages = [ {"role": "system", "content": """You are a helpful weather assistant. Give Celsius responses.Do not answer questions not related to waether."""}, {"role": "user", "content": f"{report}\nTime: {time_context}\n{aqi_info}\n{alert}\nUser asked: {user_query}"} ] try: response = client.chat.completions.create( model="gpt-3.5-turbo", messages=messages, temperature=0, max_tokens=350 ) return response.choices[0].message.content except Exception as e: return f"❌ OpenAI API Error: {e}" def get_recommendation(city, custom_city): selected_city = custom_city if custom_city else city temp, condition, lat, lon = get_weather(selected_city) if temp is None: return f"❌ Could not fetch weather for '{selected_city}'." aqi = get_air_quality(lat, lon) hour = datetime.now().hour time_context = "morning" if hour < 12 else "afternoon" if hour < 17 else "evening" system_msg = "You are a weather lifestyle advisor. Based on temperature, weather, AQI, and time of day, suggest clothes, food, and activities." user_msg = f"City: {selected_city}\nTemperature: {temp}°C\nCondition: {condition}\nTime: {time_context}\nAir Quality: {aqi}" try: response = client.chat.completions.create( model="gpt-3.5-turbo", messages=[{"role": "system", "content": system_msg}, {"role": "user", "content": user_msg}], temperature=0.3, max_tokens=300, stop=["BYE"], ) return f"{aqi}\n\n{response.choices[0].message.content}" except Exception as e: return f"❌ OpenAI API Error: {e}" # Gradio Interface with gr.Blocks(title="Weather Assistant Bot") as demo: with gr.Tabs(): with gr.TabItem("🌦️ Weather Chat"): gr.Markdown("### Ask about current weather and get advice") city = gr.Dropdown(choices=top_cities, label="Select City") custom_city = gr.Textbox(label="Or Enter Your Own City") query = gr.Textbox(label="Enter Weather-related Question") output = gr.Textbox(label="Response", lines=8) btn = gr.Button("Get Weather Info") btn.click(fn=weather_chat, inputs=[city, custom_city, query], outputs=output) with gr.TabItem("🌫️ AQI & Lifestyle Tips"): gr.Markdown("### Check Air Quality and Get Personalized Recommendations") #city2 = gr.Dropdown(choices=top_cities, label="Select City") custom_city2 = gr.Textbox(label=" Enter Your Own City") aqi_output = gr.Textbox(label="AQI & Recommendation", lines=10) aqi_btn = gr.Button("Check AQI & Get Tips") aqi_btn.click(fn=get_recommendation, inputs=[custom_city2], outputs=aqi_output) demo.launch()